Preventing onbeforeunload dialogs in IE9 - javascript

I'm having an issue in IE9 with onbeforeunload -- when the code below is run it repeatedly brings up a dialog asking if you want to stay or leave the page.
I modified my code to prevent default functioning based on this thread to no avail.
Any help on this would be much appreciated.
Code Sample:
window.onbeforeunload = function(e) {
e.preventDefault();
e.returnValue = false;
saveFormData();
return null;
}
function saveFormData() {
$.post("<?php echo site_url('resume/cleanup'); ?>", { resume_id: "<?php echo $this->session->userdata('resume_id'); ?>" } );
}

You cannot send an AJAX request while the page is unloading as most browsers block it. You should ask the user to stay on the page if there is dirty data. That's all you should do from your onbeforeunload handler
Try your code without calling $.post and it should behave as expected

The only thing you are allowed to do in an onbeforeunload handler is display a dialog. You specifically don't get any extra time to perform tasks which may take time to complete, like firing off HTTP requests — the user has asked to leave your site; aside from asking them politely whether they want to stay, you aren't allowed to make them stay (even while you clean up).
https://developer.mozilla.org/en/DOM/window.onbeforeunload

Related

Prevent user to leave page without the confirmation

I have found on StackOverflow this script that handles the issue when a user wants to leave the page, to ask him before doing it.
ISSUE
It is working fine (even though there is probably a much better solution) but I have realized that it is causing one "bug". When a user sends data from the form and the script asks him does he want to leave the page (because of the redirect) it still sends data. So, even if the user clicks on "Cancel" it will still proceed to the store() method and if the user adds something more and sends again the data I get duplicates. Is there a way to include "stop propagation" in this script?
CODE
window.onbeforeunload = function () {
return 'Are you sure you want to close this website?';
};
Additional question
Since this script is running with the Laravel Livewire, every time I click on any button related to the livewire (which won't redirect the user to the other page) script prompts the popup to ask if the user is sure he wants to leave the page. Is there any workaround (if you need some other code, write a comment because I am not sure which part could help you at all :) ) for this issue?
Try this:
<script>
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Sure?';
}
// For Safari
return 'Sure?';
};
</script>
Here is a working jsFiddle

How to stop refresh the page form the beforeunload event?

i'm using the 'beforeunload' event to detect the refresh event from the webpage.how to stop refresh the page from beforeunload event and i should not show alert message
window.addEventListener("beforeunload", this.onUnload);
onUnload = e => {
e.preventDefault();
// how to stop refresh the page from here and i should not show alert message.
//it is showing alert message. i no need to show the alert.
e.returnValue = "sure do you want to reload?";
}
It is not possible to prevent unloading a page without notifying the user.
Imagine you want to go to github.com at a time you are viewing stackoverflow.com - but it will simply prevent you from navigating away!
However, there was a time some browsers used to prevent unloading silently when you assign an empty string to the returnValue. But I believe that age of evil is gone now.
When i understand your following comment corectly, then you simply need to return zero, or false. So in your function you write:
onUnload = e => {
//e.preventDefault();
return false;
}
When i do this, i get an automated response from the Browser (for me its Chrome), if i really wanna close this website. And its in my language, so its i18n-compilant
It basically says "Are you sure you wanna refresh/close this website, data may get lost" and than 2 buttons with "Refresh/Close" and "Abort"

Direct to another page if refresh button is pressed

When the refresh button is pressed, I would like to send the user to a different page using PHP or javascript.
That is,
if (refresh pressed) header('Location: Some_Page.php');
Can anyone tell me how is it possible?
Although you tagged your question as javascript, you did also tag it as php
You could use sessions for this. Here is what I tried that worked.
I set the conditional statement to 10 (for testing purposes), but you can make it as 1 or any other number you wish.
N.B.: ob_start(); is required, otherwise it will throw an headers already sent error message.
<?php
ob_start();
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
if ($_SESSION['views']== 10){
header("Location: http://www.example.com/");
}
?>
Footnotes: If you use this, session_start(); (and maybe ob_start(); if using header()) needs to be inside all files using the same session, and at the top as shown.
So, I don't think you can hook into a specific page refresh event (I don't think it exists), you can hook into a page unload via javascript, which would be fired on a page refresh event. You would use the onunload or onbeforeunload event to trigger saving the state in cache or a cookie. (you could also on timeouts set the state every x seconds during normal gameplay)
You cannot alert or redirect with hooking into the unload or onbeforeunload events.
the following was my original suggestion, before I tested and found you cannot do the page navigation from the onunload and onbeforeunload events
You would also want to set a boolean saying game place has started, check for the boolean in the unload event (set that boolean to false after game is complete). That way you do not do a redirect when the user wants to actually navigate away from your game.
window.onbeforeunload=function(){window.location.replace(...)};
window.location.href=... would also work in the context of the onunload event.
Event click on Refresh button equals event of exiting current page. Use next:
// jQuery
$('body').bind('beforeunload',function(e){
e.preventDefault();
var url = "http://stackoverflow.com";
$(location).attr('href',url);
});
// JS
window.onbeforeunload = function (e) {
e.preventDefault();
var url = "http://stackoverflow.com";
// IE8 and lower fix
if (navigator.userAgent.match(/MSIE\s(?!9.0)/)) {
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
else window.location.replace(url);
};

Implementing "this page is asking you to confirm that you want to leave"

This is a warning that Firefox raises when I want to leave certain pages. Based on the pages I've seen this on and that this warning appears when I try to close the page after filling in the forms, I can only assume that it's working on a dynamic page. Which technology is used to implement this functionality? How can I implement it myself on a simple hello-world page?
You basically implement a handler for beforeunload event. This allows you to warn your users that they have unsaved data.
Pseudo Code:
window.onbeforeunload = function warnUsers()
{
if (needToConfirm)
{
// check to see if any changes to the data entry fields have been made
if(changesPresent) {
return message to display
}
else {
// no changes - return nothing
}
}
}
Here's a very good article that discusses this in depth: http://www.4guysfromrolla.com/webtech/100604-1.shtml Note: This link no longer exists. Here is a copy of it from the Wayback Machine:
https://web.archive.org/web/20211020134123/http://www.4guysfromrolla.com/webtech/100604-1.shtml
Note: There is onunload event also but that fires after the page has unloaded, hence is too late to take any reliable action. You should never put any critical code in onunload as that is never guranteed to execute.
Well, you need to try to add some other things like form. But something simple is:
EDIT: Fixed HTML;
<html>
<head>
<script language="javascript">
function mymessage()
{
alert("This message was triggered from the onunload event");
}
</script>
</head>
<body onbeforeunload="mymessage()">
<p>close this window and watch the warning box come up!</p>
</body>
</html>
Like the other answers have said, you can use a handler for beforeunload. To do this, you can use an eventListener:
addEventListener("beforeunload", () => {
// Do things before the page is closed.
event.preventDefault();
});
event.preventDefault() displays a message asking the user to confirm that they want to leave. You can also do something else like autosave without displaying a confirmation message.
According to MDN, returning a string or setting event.returnValue to activate the confirmation message is deprecated.

JavaScript interrupt event

Here is the situation :
If I am in page-1 now I am clicking a link from page-1 to navigate to page-2. Before page-2 is loaded I am hitting escape so that still I am staying in page-1.
At that point I want to track that event.
Is there any JavaScript event so that I can track the above scenario?
More Info :
To avoid concurrent request to the "page-2", when the user clicks a link from page-1 I am redirecting to page-2 and disabling the link (to avoid multiple request to "page-2). At this point when we hit Esc and abort loading page-2, I need to enable the link again in page-1.
I tried using this code:
<html>
<head>
<script>
document.onkeypress = KeyPressed;
function KeyPressed(e)
{
if (!e) e = window.event; //IE Compatibility
alert(e.keyCode);
}
</script>
</head>
<body>
Stack Overflow
</body>
</html>
It detects any key pressed while you're on the page. Once you click on the SO link and hit escape, nothing happens. The browser is already receiving a response from the SO server and is starting to process it, this page has already been "left", despite appearances when you see "Waiting for http://stackoverflow.com" in your browser's status bar.
Your idea of handling this event is plain wrong. Blocking the button is required to make the user unable to do double post data. However, the request is sent instantaneously(!) after the click on the link.
So, if you click the link once, stop the page, then click second time - it will submit it twice, and that is not what is intended to happen.
Two events are triggered when the page unloads.
window.onUnload
window.onBeforeUnload
You can use these events to cancel the unload of the page, however after that, there page is considered done.
What you can do is make the page wait 5 secs or so before going to the new page:
eg:
window.onunload = (function() {
var time = new Date();
var cancel = false;
window.onkeypress = function (e) {
if ((e || window.event).keyCode == 27) cancel = true;
};
while(time > new Date() - 5000) {
if (cancel) return false;
}
});
In fact that may cause some browsers to hang since you're taking up all process time given to the JS script. ie: in the while block.
You could probably avoid that by doing a blocking function call, that isn't so process intensive, like one that is bound by network latency. eg: XMLHttpRequest() etc. I don't think calls that are queued such as setTimeout() will work here, as they don't block.
Since the <a href> tag tells the browser to move to another page, it's up to it to decide if it will still have your script running. If I were it, I wouldn't listen.
If you want to override that, I guess you should tell the browser not to listen to that particular onClick event, and put a callback in place that loads the target page in the background. This assures your page is still active. After the target page has loaded (by your script), you could kindly ask the browser to update itself with the received content.
So that's the theory. I have no idea if the DOM lets you just override the content of a loaded page, but I guess it does.

Categories

Resources