Can I stop JS location.href without a popup?

I want to create an external JS-external script (tag) that stops the code (which is usually not mine) like location.href, without using a popup. I tried things like:

$(window).bind('beforeunload', function() { window.stop(); event.stopImmediatePropagation(); event.preventDefault(); location.href = '#'; }); 

but nothing helped. again, I need this without using: return "are you sure?" maybe another callback?

Thanks Dan

+6
source share
2 answers

The correct way to use onbeforeunload to confirm navigation is to simply return the line of the message you want to show. MDN has this to say .

The function must 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 are asking for will be just the same as binding to jquery, especially since onbeforeunload does not support multiple event listeners like other events do)

 window.onbeforeunload = function() { return "Are you sure?"; }; 

But ironically, Firefox does not support this for security purposes.

Please note that in Firefox 4 and later, the returned string is not displayed to the user. See error 588292 .

Edit: I read more error report. The main reason they find this solution is: "1. Remove the text provided by the site as it is a security issue (untrusted text in browser dialogs)." I wonder how they relate to alert ?

Most modern browsers (Chome, IE 9+ or earlier, and Opera, I know for sure) will ignore everything you try to do in the onbeforeunload function other than returning a string to display. This is done to prevent users from capturing the user's browser, opening pop-ups, overriding navigation attempts by specifying another user, possibly a malicious domain, etc.

Edit 2: I was clearly wrong. Only some things are forbidden in onbeforeunload , they just happen mainly in those types of things that you tried to use in your code example when dealing with event propagation and page navigation. From deep in the comments of this FF error report, user oyasumi sends a link to this jsFiddle with work to display custom text in FF 4+ users: http://jsfiddle.net/ecmanaut/hQ3AQ/ So, apparently, an alert() is still allowed even onbeforeunload , which gladly does exactly what was the original reason for fixing the "error": displaying custom text in the browser / application / OS / official dialog box.

+1
source

Have you tried using "return false"? You must also send the event to your function. here is an example where you can prevent button clicks and hyperlinks

 <input type="button" value="click me" /> <a href="www.google.com"> google </a> $(document).ready(function(){ $('input[type="button"]').click(function(e){ e.preventDefault(); }); $('a').click(function(e){ e.preventDefault(); }); }); 

here is the link http://jsfiddle.net/juTtG/143/

-1
source

All Articles