How to handle browser's window.onbeforeunload event - javascript

I want to handle window.onbeforeunload event. I can handle it this way
window.onbeforeunload = function() {
return "MSG";
}
But in this case it shows a popup asking for user confirmation i dont want that confirmation dialog instead it will directly return false like event.cancel = true.

You cannot do this in the onBeforeUnload. The for this reason is; the user has already sent in a request to move away from the page and the event has been intercepted. The confirm is the best you can do, unless you prevent the event further up the event chain (such as with onkeydown).
For instance, if you want the user to not be able to use their keyboard to go backwards and forwards in history, or to reload the page, this could be achieved using;
var catchKey = {
37: true, /// left
39: true /// right
};
window.onkeydown = function(event) {
if (catchKey[event.keyCode] && event.ctrlKey) {
event.preventDefault();
event.stopPropagation();
}
}
Hope that helps!

Basically you want to prevent the user from closing the browser window/tab or navigate away from your page at all?
I am sure no browser maker will let you do that... then the only way to close the browser in such a case would be to kill the process.
So: Not possible, as far as I can see.

Related

How can I catch opening of the link

I have a HTML page with multiple links. Is there any ability to catch the event of opening the link? Users can just click on link or can open it on the new window or tab by right click.
Links refers to external resources and I can not control of its content.
There's a few client-side options that I can think of, none of which ideal:
You could replace the link's href with a javascript: url that ran any code you wanted, and then navigated to the correct URL (location.href = "http://example.com"). This is nasty though, since it breaks if the user does right click -> new tab or has JavaScript disabled.
You can add an event listener to the click event of the <a>. But this would not get triggered on right-click -> open, or a user tabbing over and pressing enter.
You can use an onunload event handler on the document itself, but this won't tell you where the user is going, and wouldn't work if the user opened a new tab.
If you just want to track where your users are navigating to, then a server-side solution is the only foolproof way. You would have to send users to your own server, which would in turn send an HTTP 302 code to redirect the browser to the correct URL. This would, of course, require more infrastructure than you may want.
Yeah you can use javascript to do something like...
$('a').click(function(){
event.preventDefault();
$(this).alert("do something");
});
try
var links = document.getElementsByTagName('a');
for(var i = 0; i< links.length; i++) {
links[i].onmousedown = function(e) {
console.log(this.href, this)
if ((e.which && e.which == 3) || (e.button && e.button == 2)) { // not sure about IE
alert('right click');
}
}
}

detect if the user have an intention to redirect from it's page

How can I detect if a user has any intention to leave his current page and redirect to any page from my website is their any javascript function that can handle this event I have more than 25 links in my page
<script type="text/javascript">
if(//user clicks a link )
confirm("do you want to continue ?");
</script>
Is their any javascript function that can check if the user click on any link on the page
This code will intercept all clicks on links in your page.
$("a").click(function() {
// this.href will be the href of the link they clicked on
// return false from this function if you want to abort the click on the link
});
FYI, unless there are very special circumstances in your page, it's kind of obnoxious to force a user to confirm that they actually want to go to the link they just clicked on. Can you imagine how terrible the web browser would be if you had to confirm every click.
There is also a generic way to prompt if the user wants to leave your page using the onbeforeunload event.
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave?';
};
Note: this is also obnoxious unless there are very special circumstances.
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave?';
};
Bear in mind that this isn't a normal event - you can't bind to it in the standard way.
To check for values? That depends on your validation framework.
In jQuery this could be something like (very basic example):
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave?';
};
});

onbeforeunload keeps poping up an alert box when user click something

I am created a page that warns the user when they click on the (close x) button on the window. I did some reading and discovered that JavaScript had a function called onbeforeonload which can take of the job I was trying to achieve. I however found at after my implementation that, when a user clicks on anything in my window (example: save and enter) The dialog box reappears. I was wondering how I could only target the specific X button in the window.
window.onbeforeunload = function (evt) {
var message = 'Do you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
Right now the function is being called globally... this resource might help you achieve what you are looking for: http://randomdrake.com/2009/09/23/how-to-use-onbeforeunload-with-form-submit-buttons/
This is a "working as intended" behavior for IE. Anchor tag clicks, regardless of whether they navigate or not, will trigger the onbeforeunload event.
This is the workaround I used - I am not sure whether it is the best approach or not:
document.onmouseup = function () {
if (window.event.srcElement.tagName === 'A') {
// turn off your onbeforeunload handler
...
// some small time later, turn it back on
setTimeout(..., 200);
}
};

window.beforeunload called twice in Firefox - how to get around this?

I'm creating a popup window that has a beforeunload handler installed. When the "Close" file menu item is used to close the popup, the beforeunload handler is called twice, resulting in two "Are you sure you want to close this window?" messages appearing.
This is a bug with Firefox, and I've reported it here, but I still would like a way to prevent this from happening. Can you think of a sane way of detecting double beforeunload to prevent the double message problem? The problem is that Firefox doesn't tell me which button in the dialog the user elected to click - OK or cancel.
<script type="text/javascript">
var onBeforeUnloadFired = false;
window.onbeforeunload = function ()
{
if (!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
event.returnValue = "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
window.setTimeout("ResetOnBeforeUnloadFired()", 10);
}
function ResetOnBeforeUnloadFired() {
onBeforeUnloadFired = false;
}
</script>
Set a variable in the handler to prevent the dialog coming up the second time. Use setTimeout to reset it afterwards.
This is definitely a FF bug. I've reported it at https://bugzilla.mozilla.org/show_bug.cgi?id=531199
The best solution I've found is to use a flag global variable that is reset after so many milliseconds, say 500 (this ensures that the function can be called again, but not immediately after its appearance).
See last code in:
http://social.msdn.microsoft.com/Forums/en/sharepointinfopath/thread/13000cd8-5c50-4260-a0d2-bc404764966d
I've found this problem in Chrome 21, Firefox 14, IE 7-9, Safari 5 (on PC).
The following works on all of these browsers. If one removes the window.onbeforeunload function during the event this will prevent the second call. The trick is to reset the window.onbeforeunload function if the user decides to stay on the page.
var window_on_before_unload = function(e) {
var msg;
// Do here what you ever you need to do
msg = "Message for user";
// Prevent next "window.onbeforeunload" from re-running this code.
// Ensure that if the user decides to stay on the page that
// this code is run the next time the user tries to leave the page.
window.onbeforeunload = set_on_before_unload;
// Prepare message for user
if (msg) {
if (/irefox\/([4-9]|1\d+)/.test(navigator.userAgent))
alert(msg
+ '\n\nThe next dialog will allow you to stay here or continue\nSee Firefox bug #588292');
(e = e || window.event).returnValue = msg;
return msg;
}
};
// Set window.onbeforeunload to the above handler.
// #uses window_on_before_unload
// #param {Event} e
var set_on_before_unload = function(e) {
// Initialize the handler for window.onbeforeunload.
window.onbeforeunload = window_on_before_unload;
}
// Initialize the handler for window.onbeforeunload.
set_on_before_unload();
Create a global variable that is set to true inside the handler. Only show the alert/popup when this variable is false.
I use the following snippet to track the exitcount
When the page loads the following variable exitCount is initialized
if (typeof(MTG) == 'undefined') MTG = {};
MTG.exitCount=0;
and in the Window unload event
$(window).bind("beforeunload", function(){
if (MTG.exitCount<=0)
{
//do your thing, save etc
}
MTG.exitCount++;
});
I've found that instead of doing your own call to confirm(), just do even.preventDefault(); within the beforeunload event. Firefox throws up its own confirm dialog.
I'm not sure if this is the correct/standard thing to do, but that's how they're doing it.
I have a document opening another popup window with window.open. In the original window I have registered (with jquery) a listener for "unload" event like this:
var popup_window = window.open(...)
$(popup_window).on('unload', function(event) ...
I have came across this page because the event was effectively triggering twice. What I have found is that it is not a bug, it triggers twice because it fires once for "about:blank" page being replaced by your page and another for your page being unloaded.
All I have to do is to filter the event that I am interested in by querying the original event:
function (event) {
var original_url = e.originalEvent.originalTarget.URL;
if (original_url != 'about:blank')
{
... do cool things ...
}
}
I don't know if this applies to the original question, because it is a special case of a window opening another, but I hope it helps.

javascript to check when the browser window is closed

Does anyone know any way that I can use javascript to check when the browser window is closed and pop-up a confirmation dialog to ask whether the user is confirm to exit the browser or change his mind to stay?
window.onbeforeunload = function (e) {
var e = e || window.event;
//IE & Firefox
if (e) {
e.returnValue = 'Are you sure?';
}
// For Safari
return 'Are you sure?';
};
https://developer.mozilla.org/en/DOM/window.onbeforeunload
The documentation here encourages listening to the onbeforeunload event and/or adding an event listener on window.
window.addEventListener('beforeunload', function(e) {}, false);
You can also just populate the .onunload or .onbeforeunload properties of window with a function or a function reference.
Though behaviour is not standardized across browsers, the function may return a value that the browser will display when confirming whether to leave the page.
If the browser remains running after the page is closed, and if the browser processes the "onbeforeunload" event of the body element (sometimes it's disabled), and if the browser allows popup windows or mesage boxes and the ability to return false from that event to prevent the page change, then it's possible.
For an example, start typing a comment on any stackoverflow page with Javascript enabled and then navigate away from that page.
This worked for me:
function closeWin(){
var exit = confirm("Do you want to leave this window?");
if(exit==true){
//do something before closing;
}
}
body onbeforeunload="closeWin()"
This works too, unless for IE8
$(window).bind('beforeunload', function (e) {
// code to execute when browser is closed
e.$.post("func.php", { action: 'action', id_userMsg: '<?php echo $id_user; ?>' });
});

Categories