Firebase入門に最適な記事とリアルタイムデータベース体験
Firebaseとは?から簡単なWebアプリをホスティングサーバーにデプロイするまでは、 Firebaseの始め方が分りやすかった。 入門はこれだけ読めばOKだと思う。
リアルタイムデータベース
自分でも同様のアプリを作って、Firebaseの最も大きな特徴でリアルタイムデータベースという 誰かがデータを更新すると自動で他の端末にも反映される機能を体験してみた。
一番手前がChromeで、その奥がSafariで、一番奥がFirebaseのリアルタイムデータベースになる。 Chromeの入力内容が、各々で即座に反映されているのが分かる。
htmlコードは次の通り。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Welcome to Firebase Hosting</title> <script src="https://www.gstatic.com/firebasejs/3.3.2/firebase.js"></script> <script src="app.js"></script> </head> <body> <div id="message"> <h4>Input and Enter</h1> <p id="outputLabel"></p> <input type="text" id="inputText" onkeypress="return enterKeyAction(event);"></li> </div> <script> var db = firebase.database(); var testText = db.ref("/sample/io"); function enterKeyAction(e) { if(e.keyCode == 13){ var text = document.getElementById("inputText").value; testText.set({text:text}); } } testText.on("value", function(snapshot) { document.getElementById("outputLabel").innerText = snapshot.val().text; }); </script> </body> </html>
Api KeyとDB URLなどは別ファイルにして、念のためhtmlから呼び出す感じにした。
// Initialize Firebase var config = { apiKey: "<your-api-key>", authDomain: "<your-app-id>.firebaseapp.com", databaseURL: "https://<your-app-id>.firebaseio.com", storageBucket: "<your-app-id>.appspot.com", }; firebase.initializeApp(config);