Home > front end >  Firebase not working properly when added to Wordpress website
Firebase not working properly when added to Wordpress website

Time:07-19

I want to add JS code with chat functionality using Firebase database for messages and Firebase Auth for logging in and signing up to a Wordpress website to use it for customer support, yet whenever I open the website that uses that JS returns a warning and an error. Could somebody try and help me? The warning

Here's how my index.js code looks:

// initialization of the database
const firebaseConfig = {
  apiKey: "XXXXXXXXXXXXXXX",
  authDomain: "xxxxxxxxxxxx",
  databaseURL: "xxxxxxx",
  projectId: "xxxxxxx",
  storageBucket: "xxxxxxxx",
  messagingSenderId: "xxxxxxx",
  appId: "xxxxxxxxxxxxxxxxxxxxxxx"
};
firebase.initializeApp(firebaseConfig);
const db = firebase.database();
const currentUser = document.getElementById("currentUser");

// variables to be used for users
var username = "", receiver;
var path, listener;
var select = document.getElementById("odbiorcy");

// selecting a user from the list of users
select.addEventListener("change", function handleChange(event) {
  if (listener)
      path.off("child_added", listener)
  
  receiver = select.options[select.selectedIndex].text;
  document.getElementById("messages").innerHTML = "";



// fetching messages
  fetchChat = db.ref("messages/"   username   "/").child(receiver);
  listener = fetchChat.on("child_added", function (snapshot) {
      const messages = snapshot.val();
      var msg;
      if(messages.usr == receiver){
        msg = "<div class='msg rcvd'>"   urlify(messages.msg)   messages.file   "</div>";  
        document.getElementById("messages").innerHTML  = msg;
      }else{
        msg = "<div class='msg sent'>"   urlify(messages.msg)   messages.file   "</div>";
        document.getElementById("messages").innerHTML  = msg;
      }

      var messBox = document.getElementById("wiadomosci");

// checking whether the receiver is typing
      let areTheyTyping = db.ref("status/"   receiver   "/"   username);
      areTheyTyping.on("value", function (snapshot) {
      const typing = snapshot.val();

      if(typing == null)
        return;

      const status = typing.tpg;

      if (status == "yes"){
          document.getElementById("typing").style.display = "flex";
          messBox.scrollTop = messBox.scrollHeight;
      }
      else
      {
          document.getElementById("typing").style.display = "none";
          messBox.scrollTop = messBox.scrollHeight;
      }
      });

// showing the receiver's online status
      let receiversStatus = db.ref("status/"   receiver   "/connections");
      receiversStatus.on("value", function (snapshot) {
        const status = snapshot.val();

        if(status != null)
          document.getElementById("status").innerHTML = "online";
        else
          document.getElementById("status").innerHTML = "offline";
      })
  });

  path = fetchChat;
});

// logging and disconnecting
var connectionsRef = db.ref("status/"   username   "/connections");
var lastOnlineRef = db.ref("status/"   username   "/lastOnline");
var connectedRef = db.ref(".info/connected");
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
firebase.auth().onAuthStateChanged(function (user) {
  if (user)
  {
      currentUser.style.display = "block";
      currentUser.innerHTML  = firebase.auth().currentUser.email;
      document.getElementById("wyloguj").style.display = "block";
      username = firebase.auth().currentUser.displayName;

// updating the user's online status
      connectionsRef = db.ref("status/"   username   "/connections");
      connectedRef = db.ref(".info/connected");
      connectedRef.on("value", function (snapshot) {
          if (!snapshot.val()) {
              const connection = connectionsRef.push();
              connection.onDisconnect().remove();
              connection.set(true);
          }
      });
  }
  else
  {
      document.getElementById("chat-txt").setAttribute("disabled", "disabled");
      document.getElementById("zaloguj").style.display = "block";
      document.getElementById("zarejestruj").style.display = "block";
      document.getElementById("odbiorcy").style.display = "none";
  }
});

// fetching users to the list
const fetchUsers = db.ref("users/");
fetchUsers.on("child_added", function (snapshot) {
  const users = snapshot.val();
  var opt = document.createElement("option");
  opt.value = users.userId;
  opt.innerHTML = users.username;
  select.appendChild(opt);
});

// files variables
const fileButton = document.getElementById("fileButton");
const fileURL = document.getElementById("fileURL");
const fileName = document.getElementById("fileName");

// sending a file
fileButton.addEventListener("change", function (e) {
  var file = e.target.files[0];
  var storageRef = firebase.storage().ref("files/"   file.name);
  var task = storageRef.put(file);
  
  task.on(
      "state_changed",
      function progress(snapshot) {
          uploader.style.display = "block";
          var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          uploader.value = percentage;
      },
      function error(err) {},
      function complete() {
          storageRef.getDownloadURL().then((downloadURL) => {
              fileURL.value = downloadURL;
          });

          fileName.value = file.name;
      }
  );
});

// sending a message
document.getElementById("send-message").addEventListener("submit", postChat);
function postChat(e) {
  db.ref("status/"   username   "/"   receiver).set({
      tpg: "no",
  });

  e.preventDefault();
  const timestamp = Date.now();
  const chatTxt = document.getElementById("chat-txt");
  const chatval = chatTxt.value;
  var message, file;
// posting a message to the database
  if(chatval)
  {
      message = chatTxt.value;
      file = " <a href='"   fileURL.value   "'>"  fileName.value   "</a>";
      chatTxt.value = "";
      db.ref("messages/"   username   "/"   receiver   "/"   timestamp).set({
          usr: username,
          file: file,
          msg: message,
      });
      
      db.ref("messages/"   receiver   "/"   username   "/"   timestamp).set({
          usr: username,
          file: file,
          msg: message,
      });
      uploader.style.display = "none";
      fileButton.value = "";
      fileURL.value = "";
      fileName.value = "";
  }

// pushing the user's typing status to the sendTyping function
  var searchTimeout;
  document.getElementById("chat-txt").onkeypress = function() {
      if (searchTimeout != undefined)
          clearTimeout(searchTimeout);
      searchTimeout = setTimeout(callServerScript, 1000);
      sendTyping(true);
  }
}

// a function sending the user's typing status to the database (function)
function sendTyping(tmp)
{
  if (tmp) {
      db.ref("status/"   username   "/"   receiver).set({
              tpg: "yes",
      });
  } else {
      db.ref("status/"   username   "/"   receiver).set({
              tpg: "no",
      });
  }
}

// the user is not typing (function)
function callServerScript()
{
  sendTyping(false);
}

// calculating time from a timestamp variable (function)
function timeSince(date)
{
  var seconds = Math.floor((new Date() - date) / 1000);
  var interval = seconds / 31536000;

  if (interval > 1)
      return Math.floor(interval)   " years";
  interval = seconds / 2592000;

  if (interval > 1)
      return Math.floor(interval)   " months";
  interval = seconds / 86400;

  if (interval > 1)
      return Math.floor(interval)   " days";
  interval = seconds / 3600;

  if (interval > 1)
      return Math.floor(interval)   " hours";
  interval = seconds / 60;

  if (interval > 1)
      return Math.floor(interval)   " minute(s)";

  return "a few seconds";
}

// logging out (function)
function logout()
{
  firebase.auth().signOut().then(() => {
          window.location.replace("./index.html");
  }).catch((error) => {});
}

// checking if the message contains a link or is a link (function)
function urlify(text)
{
  var urlRegex = /((?:(?:http?|ftp)[s]*:\/\/)?[a-z0-9-%\/\&=?\.] \.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`] )?)/gi
  return text.replace(urlRegex, function(url) {
          return '<a href="'   url   '" target="_blank" rel="noopener norefferer">'   url   '</a>';
  })
}

And this is the way I add script to the footer of the page using "Header and Footer Code Manager"

enter image description here

This is the way I add it to the Wordpress page:

enter image description here

Could someone help me and tell me a solution? I've been working on fixing it for days...

CodePudding user response:

Looks like you use the Safari browser. The browser has problems with const and let declared in the code. Try to change those which are showed up as faulty in the browser's console to var.

Also if you use Wordpress website with you JS code you probably need to turn LScache off or exclude it on certain subpages. You can do this by entering the WP dashboard and in the Litespeed cache section open the cache options and exclude these which use JS.

Hope it helped, I used to be stuck with the same problem ;)

  • Related