I am working on a single page application at the moment, and I wanting to show some UI is a user, refreshes the page, closes the tab, or navigates away, the reason for this is doing any of these will cancel any active uploads, and I want the user to know that.
So far I have,
$(window).on('beforeunload', function() {
alert("!!!");
return null;
});
This only seems to fire when I refresh the page, though. Is there away to hook this in to my router? I have a global var called App.Uploading, if that is true, I want to fire a method every time a route is accessed is that possible?
There is a JQuery unload function you can use:
$( window ).unload(function() {
console.log('preventing unload!');
return false;
});
document.location = 'http://www.google.com';
Related
const adminLogOut = document.getElementById("adminLogOut");
adminLogOut.addEventListener('click', function () {
window.alert("Are You sure You want to leave?");
});
window.onbeforeunload = function() {
return "Are You sure You want to leave?"
}
The code above is going to prevent from logout and redirection. By redirection I mean leaving my web application stored on my local machine and run in Firefox. E.g. when I want to click on any bookmark in my browser, then .onbeforeunload function should prevent from leaving my application, but it works only when I want to leave the page which this JS code belongs to.
Would You give any advice?
The id's #switchtopagetwo and #switchtoindex are assigned to buttons that do what you can infer from the id's names. What I want to do is on click of the button, I want to redirect to the new page via window.location = url; and then run a function that renders some data on the page via pagetwoData() or pageoneData(), depending on where I am at the moment.
$('#switchtopagetwo').on('click', function () {
window.location = 'pagetwo.html';
pagetwoData();
});
//pagetwo.html button
$('#switchtoindex').on('click', function () {
window.location = 'index.html';
pageoneData();
});
When I comment out window.location, the functions run and I can see the data on the screen, but there's no page redirect even on clicking the button. When I click on the buttons fast enough, I can see the function's data being rendered for a split second and then disappearing. When I console.log certain items, I can see the console.log's appearing in the console and then disappearing the same way.
Clearly there is an issue with window.location. Is there better code I can use for clicking the button, redirecting the page to load the page-2 data, then clicking the button again to go back to page-1 data?
When you redirect to a new page, the entire page context is abandoned and replaced by the new page. Nothing which happens on the source page after that redirect can be relied upon to still happen. But anything on the target page that's loading will happen.
Instead of trying to get Page1 to tell Page2 to do something when it loads, just have that something happen on Page2. For example:
// on index.html
pageoneData();
$('#switchtopagetwo').on('click', function () {
window.location = 'pagetwo.html';
});
// on pagetwo.html
pagetwoData();
$('#switchtoindex').on('click', function () {
window.location = 'index.html';
});
Basically, for any given page, whatever you want to happen on that page when it loads should be executed on that page when it loads.
i want to put this dialog box inside the page refresh. i mean. when i refresh the page this must be the out put.
<script>
$(function() {
$("#dialog").dialog({
modal: true,
resizable: false,
buttons: {
"I want to Continue the Exam": function() {
$(this).dialog("close");
},
"I Refresh": function() {
$(this).dialog("close");
}
}
});
});
</script>
As far as I know, when you 'refresh' a page then all the JS objects are destroyed (those that are written in script).In other words the script is re-loaded. So you can't persist your script while the page is in transition.
Type I (classical Single Page App)-
So if you simply want to reload a particular part of the Application then use $.ajax() methods like beforeSend() for showing whatever (alert or best a loading spinner/div) you want during the data request or 'page-refresh'. And then you can hide them on done().
Type II (using routers)
JS frameworks like Angular give you options to reload a particular route of your App without reloading/refreshing your entire app - $route.reload(). You can show/hide some div/directive based on manipulation in your controller.
So you have to use some form of asynchronous scripting to deal with this "PROMPT while REFRESH" situation.
Using $.ajax() to simulate (pseudo code)-
$.ajax({
url: "_URL_to_get_or_post_data__",
beforeSend: function( xhr ) {
$popup.show();
}
})
.done(function( data ) {
$popup.hide();
}
});
Browsers have a security feature that will not let a page prevent users from leaving the page. By leaving a page it means closing tab/browser, navigating to a different page or refreshing. The only way to stop the user is to assign a function to onbeforeunload. Like this:
onbeforeunload = function () { return "You have unsaved data. Are you sure you want to exit?"; }
This message is synchronous, it will stop all javascript running on the page. If user presses ok the browser will leave the page (or refresh) else it will stay on the page.
EDIT
Usage: when user have changed something and have unsaved data - you assign a function to onbeforeunload:
onbeforeunload = function () { return "some message"; }
after the data is saved set onbeforeunload to null:
onbeforeunload = null;
I'm trying to achive the following:
On page A we have an access restricted Link to page B. The access restriction is handled on the server side in PHP.
When a user clicks on this link to page B we display a modal dialogue on page A (via javascript) with a form, having the link's href (B) as the action. (To give the user an immediate feedback. The fallback is to redirect him to a login form that redirects him to the site he wants to access.)
This system works quite well.
But now comes my question:
We have access restricted links that should be opened in a new window.
Now if I use target="_blank" on the form the user stays logged out on the page he came from (A), that is still open in the background.
Is there a way to reload the page (A, in the background) right after the form has been submitted to the new window (B)?
My first idea was to use window.location.reload(); in the submit handler on page A.
This didn't work in chrome and from what I understand could create a race condition.
Another idea would be to log the user in via an ajax call and open a new window through javascript. Is there a way to do this without having to deal with pop-up blockers?
I implemented the idea of lostsource (see below) with one slight addition.
As I need to reload only once, the timer of setInterval can be stopped if the cookie changed.
var ri=setInterval(function() {
if(oldCookie != document.cookie) {
// assuming a login happened, reload page
clearInterval(ri);
window.location.reload();
}
},1000); // check every second
I still love the idea. stackoverflow is awsome!
Assuming you're storing PHP session information inside a cookie, you might be able to monitor your document.cookie for changes.
Before submitting the form store the value of the current cookie and monitor it for changes with a timer:
form.onsubmit = function() {
var oldCookie = document.cookie;
var cookiePoll = setInterval(function() {
if(oldCookie != document.cookie) {
// stop polling
clearInterval(cookiePoll);
// assuming a login happened, reload page
window.location.reload();
}
},1000); // check every second
}
On the parent page, do you have any visual/functional changes because of the login? As in any new actions possible?
If not, then you dont have to do anything as you would be checking for login on every action from the parent page, you can check for permissions along with that.
If there are changes or additional functionalities, you can call a javascript function in the parent, say reloadMe, using window.opener.reloadMe()
Why not just a simple setTimeout
setTimeout(function(){ location.reload(); }, 1000);
It is a bit hacky, but seems appropriate for your situation.
I have to do some kind of operation on the page refresh or reload. that is when I hit next page or Filter or refresh on the grid. I need to show some confirmation box over this Events.
is there any event which can tell you page is doing filer? refresh or paging? using javascript?
Thanks
If it is refreshing (or the user is leaving the website/closing the browser), window.onunload will fire.
// From MDN
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
https://developer.mozilla.org/en/DOM/window.onunload
If you just want a confirmation box to allow them to stay, use this:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
You can create a hidden field and set its value on first page load. When the page is loaded again, you can check the hidden field. If it's empty then the page is loaded for the first time, else it's refreshed. Some thing like this:
HTML
<body onLoad="CheckPageLoad();">
<input type="hidden" name="visit" id="visit" value="" />
</body>
JS
function CheckPageLoad() {
if (document.getElementById("visit").value == "") {
// This is a fresh page load
document.getElementById("visit").value = "1";
}
else {
// This is a page refresh
}
}
There are some clarification notes on wrestling with this I think are critical.
First, the refresh/hidden field system works on the beginning of the new page copy and after, not on leaving the first page copy.
From my research of this method and a few others, there is no way, primarily due to privacy standards, to detect a refresh of a page during unload or earlier. only after the load of the new page and later.
I had a similar issue request, but basically it was terminate session on exit of page, and while looking through that, found that a browser treats a reload/refresh as two distinct pieces:
close the current window (fires onbeforeunload and onunload js events).
request the page as if you never had it. Session on server of course has no issue, but no querystring changes/added values to the page's last used url.
These happen in just that order as well. Only a custom or non standard browser will behave differently.
$(function () {
if (performance.navigation.type == 1) {
yourFunction();
}
});
More about PerformanceNavigation object returned by performance.navigation