Leaving a page - message appears twice - javascript

I've added this Javascript to my website which detects when the user navigates away from the page, but I only want a warning to appear if the navigator is offline AND one of my elements contains the word "unsaved":
window.thisPage = window.thisPage || {};
window.thisPage.closeEditorWarning = function (event) {
if (navigator.onLine===false) {
// See if any fields need saving...
for (i = 1; i <= 500; i++) {
try {
ToSave = document.getElementById("Q" + i).innerHTML;
if (ToSave.indexOf("unsaved")!=-1) {
return "You are currently offline and some of your responses are not yet saved.\r\n\r\nIf you want to save the changes you've made, choose to 'Stay on this Page' and then reconnect to the internet and any unsaved responses will save automatically.";
}
}
catch(err) { }
// If got this far, nothing needs saving anyway...
}
}
return undefined;
};
window.onbeforeunload = window.thisPage.closeEditorWarning;
The code works fine except; if the message pops up the first time and I choose "Stay on this page", then try to navigate away again and the second time click "Leave this page" - rather than navigating away it displays the message again but I can't work out why.

Try returning true from your catch, so the unload will execute. You can also remove the return undefined; from the end.
This works for me, is this what you're after?
This works for me in Firefox.
Fiddle: http://jsfiddle.net/518myq0j/3/ (clicking 'Run' triggers the onbeforeunload)
Updated JavaScript code:
window.thisPage = window.thisPage || {};
window.thisPage.closeEditorWarning = function (event) {
if (navigator.onLine === false) {
// See if any fields need saving...
for (i = 1; i <= 5; i++) {
try {
var ToSave = document.getElementById("Q" + i).innerHTML;
if (ToSave.indexOf("unsaved") != -1) {
return "You are currently offline and some of your responses are not yet saved.\r\n\r\nIf you want to save the changes you've made, choose to 'Stay on this Page' and then reconnect to the internet and any unsaved responses will save automatically.";
}
} catch (err) {
return true;
}
}
}
};
window.onbeforeunload = window.thisPage.closeEditorWarning;

Related

Save in localstorage and db and show it later

I use Elementor Pro.
I have a button that is limited to 7 clicks, when clicking number 7 is disabled, and this is saved in localstorage to display later.
My problem if the user login from different device, the count start againg in 0. and obviously the code don't work for my need, The user after 7 click Never can click again.
How can resolve this?
this is the code:
<script>
// On page load (or in whatever event creates the button)
window.addEventListener("load", ()=>{
// Read the saved state from local storage (if not yet saved, will be null)
let clickcount3 = localStorage.getItem("localStorage.clickcount3");
if(localStorage.clickcount3>6)
document.getElementById("showResultMasPack").style.visibility = "visible";
});
function CounterMastPack() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount3) {
localStorage.clickcount3 = Number(localStorage.clickcount3)+1;
} else {
localStorage.clickcount3 = 1;
}
document.getElementById("resultMastPack").innerHTML = localStorage.clickcount3 + " Click(s).";
} else {
document.getElementById("resultMastPack").innerHTML = "Sorry, your browser does not support web storage...";
}
if(localStorage.clickcount3>6)
document.getElementById("showResultMasPack").style.visibility = "visible";
}
</script>

Service Worker onClick event - How to open url in window withing sw scope?

I have service worker which handles push notification click event:
self.addEventListener('notificationclick', function (e) {
e.notification.close();
e.waitUntil(
clients.openWindow(e.notification.data.url)
);
});
When notification comes it takes url from data and displays it in new window.
The code works, however, I want different behavior. When User clicks on the link, then it should check if there is any opened window within service worker scope. If yes, then it should focus on the window and navigate to the given url.
I have checked this answer but it is not exactly what I want.
Any idea how it can be done?
P.S. I wrote this code but it still doesn't work. The first two messages are however shown in the log.
self.addEventListener('notificationclick', function (e) {
e.notification.close();
var redirectUrl = e.notification.data.redirect_url.toString();
var scopeUrl = e.notification.data.scope_url.toString();
console.log(redirectUrl);
console.log(scopeUrl);
e.waitUntil(
clients.matchAll({type: 'window'}).then(function(clients) {
for (i = 0; i < clients.length; i++) {
console.log(clients[i].url);
if (clients[i].url.toString().indexOf(scopeUrl) !== -1) {
// Scope url is the part of main url
clients[i].navigate(givenUrl);
clients[i].focus();
break;
}
}
})
);
});
Ok, here is the piece of code which works as expected. Notice that I am passing scope_url together with redirect_url into the web notification. After that I am checking if scope_url is part of sw location. Only after that I navigate to redirect_url.
self.addEventListener('notificationclick', function (e) {
e.notification.close();
var redirectUrl = e.notification.data.redirect_url;
var scopeUrl = e.notification.data.scope_url;
e.waitUntil(
clients.matchAll({includeUncontrolled: true, type: 'window'}).then(function(clients) {
for (i = 0; i < clients.length; i++) {
if (clients[i].url.indexOf(scopeUrl) !== -1) {
// Scope url is the part of main url
clients[i].navigate(redirectUrl);
clients[i].focus();
break;
}
}
})
);
});
If I understand you correctly, most of the code you linked to works here.
First retrieve all the clients
If there are more than one, choose one of them
Navigate that to somewhere and focus
Else open a new window
Right?
event.waitUntil(
clients.matchAll({type: 'window'})
.then(clients => {
// clients is an array with all the clients
if (clients.length > 0) {
// if you have multiple clients, decide
// choose one of the clients here
const someClient = clients[..someindex..]
return someClient.navigate(navigationUrl)
.then(client => client.focus());
} else {
// if you don't have any clients
return clients.openWindow(navigationUrl);
}
})
);

prevent pop up after refresh the page

I'm creating a popup that will show when the user scrolls. However when the user clicks on the close button and refreshes the page and scrolls, I need to make a popup to show up after 10 minutes.
var popUp= document.getElementById("popup");
var closePopUp= document.getElementsByClassName('popup-close');
var halfScreen= document.body.offsetHeight/2;
var showOnce = true;
//show when scroll
window.onscroll = function(ev) {
if ((window.innerHeight+window.scrollY) >= halfScreen && showOnce) {
if(popUp.className === "hide"){
popUp.className = "";
}
showOnce = false;
}
};
//close button
for(var i = 0; i<closePopUp.length; i++){
closePopUp[i].addEventListener('click', function(event) {
if(popUp.className === ""){
popUp.className = "hide";
}
});
}
First you should detect whether the user has refreshed the page.You can achieve this using navigator object.Refer this question for implementation.
Secondly, once the user refreshes the page all the variables gets destroyed and initialized again.Hence you must use cookies or server side sessions to store whether user has already closed it once.But I always recommend you to setup sessions since cookies can be disabled by users.
To sum it up,setup an ajax request once the user refreshes the page,and if already he has closed the popup once, start a timeout for 10 minutes.
Adding a sample prototype for this :
var refreshed = false;
if (performance.navigation.type == 1) {
console.info( "This page is reloaded" );
refreshed = true;
} else {
console.info( "This page is not reloaded");
refreshed = false;
}
if(refreshed) {
//implement this ajax function yourself.
ajax('path/to/yourserver','method','data',function(response) {
if(response == "showed") {
var time = 10 * 60 * 1000;//10 minutes.
setTimeout(function() {
//show your popup.
},time);
}else {
//immediately show once scrolled.
}
});
}
You should use cookie for this and set cookie expiration time for 10 minutes take a look at this cookie plugin hope it helps
Set a cookie
$.cookie("example", "foo"); // Sample 1
$.cookie("example", "foo", { expires: 7 }); // Sample 2
Get a cookie
alert( $.cookie("example") );
Delete the cookie
$.removeCookie("example");
Or there is an example which is given in this answer take a look at this also

How do it look in Jquery

Hello StackOver Flow friends!
Please I am a newbie
I need to convert this code to Jquery!
I am working on it but unable to make it work. I am learning javascript but I want to see how do the same code work in Jquery. What all I need.
Now, What this function do is:
When an audio starts and as the time limit of 30 sec gets over. It Shows a confirm box whether to login for listening to the audio further or not.
If user clicks 'OK' it redirects to a login page and If the User clicks close or cancel it refreshes the page. Now What I need is that I need to make the confirm box appear with css style. So I need to change it to jquery . Or what the Masters of code think would be perfect.
<script>
document.addEventListener("play", function (e) {
var audios = document.getElementsByTagName("audio");
for (var i = 0, len = audios.length; i < len; i++) {
if (audios[i] === e.target) {
e.target.addEventListener("canplaythrough", function () {
setTimeout(function () {
e.target.pause();
var r = confirm("Please Log in for more than 30s preview!");
if (r == true) {
//x = "You pressed OK!";
window.location.href = "https://www.google.com";
} else {
//x = "You pressed Cancel!";
location.reload();
}
},
30000);
}, false);
}
}
}, true);
</script>

to show alert message when user closes particular page for first time

I have jquery which shows alert message when page loads for first time and not again but now i want jquery which shows alert message when page is closed for first time only Please can anyone help me what changes can be made in give jquery which is for page load?
<script type="text/javascript">
// First Time Visit Processing
// copyright 10th January 2006, Stephen Chapman
// permission to use this Javascript on your web page is granted
// provided that all of the below code in this script (including this
// comment) is used without any alteration
function rC(nam)
{
var tC = document.cookie.split('; ');
for (var i = tC.length - 1; i >= 0; i--)
{
var x = tC[i].split('=');
if (nam == x[0])
return unescape(x[1]);
}
return '~';
}
function wC(nam,val)
{
document.cookie = nam + '=' + escape(val);
}
function lC(nam,pg)
{
var val = rC(nam);
if (val.indexOf('~'+pg+'~') != -1)
return false;
val += pg + '~';
wC(nam,val);
return true;
}
function firstTime(cN)
{
return lC('pWrD4jBo',cN);
}
function thisPage()
{
var page = location.href.substring(location.href.lastIndexOf('\/')+1);
pos = page.indexOf('.');
if (pos > -1)
{
page = page.substr(0,pos);
}
return page;
}
// example code to call it - you may modify this as required
function start() {
if (firstTime(thisPage())) {
// this code only runs for first visit
alert('welcome');
}
// other code to run every time once page is loaded goes here
}
onload = start;
</script>
That's really overcomplicating things?
To alert a message the first time any page loads, you'd do:
if ( ! localStorage.getItem(window.location) ) {
localStorage.setItem(window.location, true);
alert('Welcome');
}
You can't really alert anything on beforeunload, but you can pop up a confirm dialog:
window.onbeforeunload = function(e) {
if ( ! localStorage.getItem('unload_' + window.location) ) {
localStorage.setItem('unload_' + window.location, true);
return 'Dialog text here.';
}
}
Support for older browsers can be added with the localStorage shim from MDN.

Categories

Resources