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

32 views Asked by At

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?

1

There are 1 answers

2
HotSanta1234 On

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>