<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<div>
名前:<input type="text" id="uname">
</div>
<div>
<textarea id="text" cols="30" rows="10"></textarea>
<button id="send">送信</button>
</div>
<div id="output" style="overflow: auto;height: 300px;"></div>
</div>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.1/firebase-app.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import { getDatabase, ref, push, set, onChildAdded, remove, onChildRemoved }
from "https://www.gstatic.com/firebasejs/9.22.1/firebase-database.js";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "×××××××××",
authDomain: "×××××××××",
databaseURL: "×××××××××",
projectId: "×××××××××",
storageBucket: "×××××××××",
messagingSenderId: "×××××××××",
appId: "×××××××××"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const dbRef = ref(db,"chat");
const output = document.getElementById("output");
const uname = document.getElementById("uname");
const text = document.getElementById("text");
//データ登録
send.addEventListener("click",function() {
const msg = {
uname: uname.value,
text: text.value
}
const newPostRef = push(dbRef);
set(newPostRef, msg);
});
//データ登録
text.addEventListener("keydown",function(e){
console.log(e);
if(e.keyCode == 13){
const msg = {
uname: uname.value,
text: text.value
}
const newPostRef = push(dbRef);
set(newPostRef, msg);
}
});
onChildAdded(dbRef, function(data){
const msg = data.val();
const key = data.key;
let new_element = document.createElement('p');
new_element.textContent = msg.uname + ':' + msg.text;
output.appendChild(new_element);
});
</script>
</body>
</html>
More than 1 year has passed since last update.
【Firebase】Realtime Databaseを使ってチャットを作る。
Posted at
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme