I want to build a JS external script ( tag) which stops code (which usually isn't mine) like location.href from happening without the use of a popup. I tried things like:
$(window).bind('beforeunload', function() {
window.stop();
event.stopImmediatePropagation();
event.preventDefault();
location.href = '#';
});
but nothing seemed to help. again, I need it without the use of the: return "are you sure?" maybe a different callback?
Thanks, Dan
Disable a link #remove the href attribute so that it can no longer receive the focus. add a role="link" so that it is always considered a link by screen readers. add an attribute aria-disabled="true" so that it is indicated as being disabled.
The href property of the Location interface is a stringifier that returns a string containing the whole URL, and allows the href to be updated.
The location. href property sets or returns the entire URL of the current page.
The right way to use onbeforeunload
to confirm navigating away is to just return the string of the message you want to have shown. MDN has this to say.
The function should assign a string value to the returnValue property of the Event object and return the same string
So your onbeforeunload
function for the behavior you ask for would just be (same as binding it with jquery, especially since onbeforeunload does not support multiple event listeners like other events do)
window.onbeforeunload = function() {
return "Are you sure?";
};
But ironically, Firefox doesn't support this for security purposes.
Note that in Firefox 4 and later the returned string is not displayed to the user. See bug 588292.
Edit: I read more of the bug report. The main reason they site for this decision is: "1. Remove the site-supplied text, since this is a security issue (untrusted text in browser dialogs)". I wonder how they feel about an alert
?
Most modern browsers (Chome, IE 9+ or earlier, and Opera, I know for sure) will ignore anything you try to do in an onbeforeunload
function other than returning a string for display. This is to prevent hijacking the users browser, opening popups, overriding navigation attempts by pointing the user another, possibly malicious domain, etc.
Edit 2: I was apparently incorrect. Only some things are disallowed in onbeforeunload
, they just happen to mainly be the types of things you tried in your sample code, having to do with event propagation and page navigation. From deep in the comments of that FF bug report, user oyasumi posts a link to this jsFiddle with a work around for displaying custom text to FF 4+ users: http://jsfiddle.net/ecmanaut/hQ3AQ/ So apparently calling alert()
is still allowed, even in onbeforeunload
, which hilariously is doing exactly what the was original reason for the 'bug' "fix": displaying custom text in a browser/application/OS/official-looking dialog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With