Quiero agregar código JS con funcionalidad de chat usando la base de datos Firebase para mensajes y Firebase Auth para iniciar sesión y registrarme en un sitio web de WordPress para usarlo para atención al cliente, pero cada vez que abro el sitio web que usa ese JS devuelve una advertencia y un error . ¿Alguien podría intentar ayudarme?
Así es como se ve mi código index.js:
// 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 + "https://stackoverflow.com/").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 + "https://stackoverflow.com/" + 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 + "https://stackoverflow.com/" + 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 + "https://stackoverflow.com/" + receiver + "https://stackoverflow.com/" + timestamp).set({
usr: username,
file: file,
msg: message,
});
db.ref("messages/" + receiver + "https://stackoverflow.com/" + username + "https://stackoverflow.com/" + 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 + "https://stackoverflow.com/" + receiver).set({
tpg: "yes",
});
} else {
db.ref("status/" + username + "https://stackoverflow.com/" + 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>';
})
}
Y esta es la forma en que agrego el script al pie de página de la página usando «Administrador de código de encabezado y pie de página»
Esta es la forma en que lo agrego a la página de WordPress:
Alguien podría ayudarme y decirme una solución? Llevo días trabajando para arreglarlo…