window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', "G-HNW0Q7GDJS", { 'send_page_view': false });
var toSend = {}
gtag('event', 'page_view', toSend)
¿Quiere recibir notificaciones de alertas?
var config = {
apiKey: "AIzaSyBklh7K_zC_uBsyBFmAOR9R0Gf31X1BwUc",
authDomain: "prod-628de.firebaseapp.com",
projectId: "prod-628de",
storageBucket: "prod-628de.appspot.com",
messagingSenderId: "363093831106",
appId: "1:363093831106:web:5df135b7cdc3d46955ba5b",
};
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toUTCString();
} else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
window.onload = function () {
firebase.initializeApp(config);
const pushModal = document.querySelector('.notificacion-modal');
const messaging = firebase.messaging();
messaging.usePublicVapidKey("BOdmAQgqdAAM4SxiE2nmyP4c-kpfouVzPzqXJYdytAA1ykeZHp3Ni3G3QSUaWO0mvMEvOc-UX4HPcofDb-r4uEE");
if(pushModal){
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is ed 1');
navigator.serviceWorker.(`/sw.js?messagingSenderId=${config.messagingSenderId}&projectId=${config.projectId}&apiKey=${config.apiKey}&appId=${config.appId}&version=F`)
.then(function(registration) {
if (!navigator.serviceWorker.controller) {
return;
}
var preventDevToolsReloadLoop;
navigator.serviceWorker.addEventListener('controllerchange', function (event) {
if (preventDevToolsReloadLoop) return;
preventDevToolsReloadLoop = true;
console.log('Controller loaded');
window.location.reload();
});
console.log('Service Worker is ed', registration);
messaging.useServiceWorker(registration);
pushModal.querySelector('.btn--link').addEventListener('click', function () {
createCookie("notificacion2", 'false', );
pushModal.style.display = "none";
});
if (!readCookie("notificacion2") && Notification.permission == 'default') {
pushModal.style.display = "block";
pushModal.querySelector('.aceptar').addEventListener('click', function () {
pushModal.style.display = "none";
requestNotification();
});
}
if (Notification.permission != 'default') requestNotification();
})
.catch(function (error) {
console.error('Service Worker Error', error);
});
} else {
console.warn('Push messaging is not ed');
}
} else {
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is ed');
navigator.serviceWorker.(`/sw.js?messagingSenderId=${config.messagingSenderId}&projectId=${config.projectId}&apiKey=${config.apiKey}&appId=${config.appId}&version=F`)
.then(function (registration) {
console.log('Service Worker is ed', registration);
messaging.useServiceWorker(registration);
requestNotification();
})
.catch(function (error) {
console.error('Service Worker Error', error);
});
} else {
console.warn('Push messaging is not ed');
}
}
function doPost(url, body, get, cb) {
var xhr = new XMLHttpRequest();
if (get)
xhr.open("GET", url);
else
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
if (body)
xhr.send(JSON.stringify(body));
else
xhr.send("");
xhr.onload = function() {
cb(xhr.status != 200 ? "error" : null)
console.log(`doPost fin: ${xhr.status} ${xhr.response}`);
};
xhr.onerror = function() {
cb("error")
console.log(`doPost fin error red`);
};
}
function requestNotification() {
console.log("aqui request notificaction")
messaging
.requestPermission()
.then(function () {
console.log("Notification permission granted firebase.");
messaging.getToken().then(function (currentToken) {
if (currentToken) {
sendTokenToServer(currentToken);
} else {
console.log('No Instance ID token available. Request permission to generate one.');
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch(function (err) {
console.log('An error occurred while retrieving token. ', err);
setTokenSentToServer(false);
});
})
.catch(function (err) {
console.log("Unable to get permission to notify.", err);
});
}
messaging.onMessage(function(payload) {
console.log("onMessage" , payload)
const notificationTitle = payload.data.title;
const notificationOptions = {
icon: 'img/push/notification.png',
badge: 'img/push/badge.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
nota: payload.data.nota,
id_notificacion: payload.data.id_notificacion
}
};
if (payload.data.image)
notificationOptions.image = payload.data.image
if(payload.data && payload.data.body ){
if( payload.data.body.indexOf("...")!= -1 )
notificationOptions["body"]=payload.data.body.replace("...","")
else
notificationTitle=payload.data.body
}
if (!("Notification" in window)) {
console.log("This browser does not system notifications");
} else if (Notification.permission === "granted") {
try {
var notification = new Notification(notificationTitle,notificationOptions);
notification.onclick = function(event) {
event.preventDefault();
if (payload.data.nota)
window.open(payload.data.nota, '_blank');
notification.close();
}
}
catch(e) { //TODO MOSTRAR LA NOTIFICACION EN EL HTML ?
console.log("Error al mostrar notificacion en primer plano", e)
}
}
});
messaging.onTokenRefresh(function() {
messaging
.getToken()
.then(function(refreshedToken) {
console.log("Token refreshed.");
setTokenSentToServer(false);
sendTokenToServer(refreshedToken);
})
.catch(function(err) {
console.log("Unable to retrieve refreshed token ", err);
showToken("Unable to retrieve refreshed token ", err);
});
});
var KEY_TO_SAVE = "sentToServer_6";
function isTokenSentToServer() {
var val = window.localStorage.getItem(KEY_TO_SAVE);
if (!val) return false;
val = new Date(val)
var today = isToday(val);
console.log("isTokenSentToServer: " + val + " -> " + today)
return today;
}
const isToday = (someDate) => {
if (!someDate instanceof Date) return false;
const today = new Date()
return someDate.getDate() == today.getDate() &&
someDate.getMonth() == today.getMonth() &&
someDate.getFullYear() == today.getFullYear()
}
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer()) {
console.log("Sending token to server...");
doPost("/webpush/subscribe", {
token: currentToken
}, null, function(err) {
if (!err) {
console.log("Token sended");
setTokenSentToServer(true);
}
});
} else {
console.log(
"Token already sent to server so won't send it again " +
"unless it changes"
);
}
}
function setTokenSentToServer(sent) {
window.localStorage.setItem(KEY_TO_SAVE, sent ? new Date() : null);
}
//function isTokenSentToServer() {
// return window.localStorage.getItem("sentToServer") === 1;
//}
//function setTokenSentToServer(sent) {
// window.localStorage.setItem("sentToServer", sent ? 1 : 0);
//}
}