简体   繁体   中英

Is there a way to update all active webpages once my firebase Realtime database gains more data?

Using firebase, I made a chatroom in HTML. It stores the data, names and messages, in a firebase real-time database. If you manually reload the page, it shows all sent messages, and if you send a new message then it also updates the field. But, if someone sends a message, another person won't be able to see it without reloading or sending a message. Is there a way to update all active pages once a new message is added to the database?

To correct the issue, I followed samthecodingman advice and used an child_added code. Removed personals about firebase, but my HTML follows closely to the below

 <script> // Your web app's Firebase configuration var firebaseConfig = { apiKey: "-", authDomain: "-", projectId: "-", storageBucket: "-", messagingSenderId: "-", appId: "-" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); // -- ADDED THIS CODE TO MAKE IT WORK -- // Get the data at the root reference var dbRef = firebase.database().ref().child("messagesAndNames"); dbRef.on("child_added", function(snapshot) { loadTextFromDatabase(); }); // -- ADDED ABOVE CODE TO MAKE IT WORK -- </script> <script> function loadTextFromDatabase(){ var dbRef = firebase.database().ref().child("messagesAndNames"); var str = ""; dbRef.once('value',(snapshot)=>{ snapshot.forEach(function(data){ str = data.val().message + "<br/>" + str; str = data.val().name.replace("\"","[").replace("\"","]") + ": " + str; }); document.getElementById("messageInput").innerHTML = str; }); } </script>
 <body onload = "loadTextFromDatabase()"> <p id="messageInput"></p> </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM