As title, I have this piece of code in my AngularJS project:
window.onbeforeunload = function (e) {
e.preventDefault();
if ($sessionStorage.toReload) {
return 'Are you sure?';
}
};
It works correctly if developer tool window is open, but it doesn't during normal execution. It happens both in Chrome and Firefox.
How can I fix it?
Ok, so the documentation page has the answer:
Note also, that various browsers ignore the result of the event and do
not ask the user for confirmation at all. In such cases, the document
will always be unloaded automatically. Firefox has a switch named
dom.disable_beforeunload in about:config to enable this behavior. As
of Chrome 60, the confirmation will be skipped if the user has not
performed a gesture in the frame or page since it was loaded. Pressing
F5 in the page seems to count as user interaction, whereas
mouse-clicking the refresh arrow or pressing F5 with Chrome DevTools
focused does not count as user interaction (as of Chrome 81).
Related
Upon clicking the back button in the browser, I would like to prevent the default behaviour of going one page back and instead do an action. I'm using the "popstate" event listener. The following function (I'm using Vue 2) works in all major browsers and even in Firefox for Android, but when I test it in Chrome for Android, it simply goes back one page without popstate being triggered at all.
mounted() {
history.pushState(null, null, <current-url>);
window.addEventListener("popstate", () => { alert(1) });
}
I tried wrapping the popstate event inside the load event and giving it a timeOut of 0, but it still didn't work specifically in Chrome for Android. The version I'm testing on is 93.
I did some more research and it seems that Chrome won't let you use popstate if there is no user interaction first. As long as you click on something or scroll down on mobile, popsate will work, otherwise it won't. I tried to simulate user interaction with click(), but that didn't work either. It seems Chrome wants genuine user interaction. I also realized this is sort of a duplicate of: Chrome popstate not firing on Back Button if no user interaction
I am implementing desktop notifications in a website which displays notifications when new messages arrive. I want the browser tab in which the site is open to get focus when the user clicks on the notification & I could get this worked in Chrome with the following code:
var n = new Notification('Title', {
'body': 'Sample content.'
});
n.onclick = function (e) {
window.focus();
};
But unfortunately, this doesn't work in Firefox. :( Could anyone tell me what I am missing here? I am testing in Chrome 31 & Firefox 26
Thanks.
In Firefox focusing window from JS is disabled due to security reasons. You have to switch flag dom.disable_window_flip to false in about:config. But by default it is disabled. The interesting moment is that in Chrome focusing window is disabled too except in response to user actions (such as click) and that's only reason why clicking on notifications works in Chrome.
Below is my code to detect and stop the browser's back button in iPad browsers.
$(window).bind("pagehide", function(e) {
})
How can I stop the page going back on browsers' back button click in iPad browsers?
You can use the onbeforeunload event that triggers when a user is leaving your page, whether it's by hitting the back button, entering a new URL or closing the browser.
Here is an example:
window.onbeforeunload = function(){
return 'You are leaving!?';
}
And here is the result on Chrome:
This event seems to be inconsistent across browsers as some will not support it, some will execute whatever function you pass it, and some will reject the function if it doesn't return a string to put in the confirmation box.
As commenter Alex Wayne stated, think twice about this. It can really create a negative impact on your site or webapp to alter the native behaviour of the back button.
I know this is not recommended, but I need it because I have an iframe inside the page who has the actual content and I want that when the users hits refresh button, iframe reloads not entire page.
I know I have to call onunload / onbeforeunload event, but I don't want to ask me if I want to leave the window, just don't.
Is that possible? I've got handled the F5 key, but I like to prevent refreshing from button too.
UPDATE: I wrote this 5 years ago, browsers do different stuff now, you can still use this for testing your browser set, but your experience may vary from my old research.
Experimenting using jQuery, because I'm lazy.
Theoretically, preventing the default behavior should stop the event from doing whatever it is supposed to do. It doesn't work with the events in my example and has different results in different browsers. I put the Math.random() in to determine if the page has been reloaded or not. Because different browsers do different things, I highly recommend NOT using this in a production environment.
<body>
<p></p>
<script type="text/javascript">
$('p').append(Math.random());
$(window).bind({
beforeunload: function(ev) {
ev.preventDefault();
},
unload: function(ev) {
ev.preventDefault();
}
});
</script>
</body>
Using CTRL-R or F5 or Reload Button:
Safari: Does nothing
Chrome: Does nothing
Opera 10 & 11: Does nothing
Firefox 7.x: Shows a special prompt with two buttons:
Stay on Page - Does not reload page
Leave Page - Reloads the page
IE7 & IE8: Shows a prompt with two buttons:
OK - Reloads the page
Cancel - Does not reload the page
IE9: Shows a prompt with two buttons:
Leave this page - reloads
Stay on this page - does not reload
Firefox Prompt (you can tell I tested it on a Mac)
IE7 & IE8 Prompt
IE9 Prompt
In closing:
Yes, I did not test IE6, I deleted my VM which had it installed, I don't have a VM with IE10 beta installed, so you're out of luck on that too.
You might also experiment with cancelBubble and stopPropagation or maybe return false; might reveal something useful. I'm down with Jordan's reply that you shouldn't be trying to override the defaults, so I'm concluding my experiment here.
Returning false in an onsubmit event prevents the form from being submitted and stays in the same page without any user interaction..
For example..
when a form having input field is empty and submitted this javascript check for validation and returns accordingly..
If false is returned nothing is done(i.e. page is not refreshed or redirected)..
If the validation is ok and if true is returned the form action is performed..
function validateForm(Str) {
mystring=document.getElementById('inputid').value;
if(!mystring.match(/\S/)){
alert ('Please Enter a String.Field cannot be empty');
return false;
}else{
return true;
}
}
I want to open new window if "F2" pressed. Below code gives me newWindow is null error message in firefox. If I don't use pop-up blocker it works. The same in IE. It work in chrome even with pop-up blocker on.
using jstree pre 1.0 stable
hotkeys: {
"f3" : function () {
url = "http://www.vse.cz";
var newWindow = window.open(url, '_blank');
newWindow.focus();
return false;
},
Q1: Can I make it work for all browsers so users don't have to change their settings when using hotkeys plugin?
Q2: How come Using JavaScript instead of target to open new windows works without any troubles in firefox? Is that because it's a link and not using hotkeys plugin?
My understanding is that the script from above page somehow
manipulates what happens
when user clicks a link. It changes the properties of the click so
browsers "don't know" that it's new window so pop-up blocker is
bypassed.
In my case I use pure js function triggered by something else, not by
a user click. And that 'my function' doesn't changes properties of any html objects. I think this is the difference. I am not sure if I am
right here.
Unfortunately, there's nothing you can do to open a new window on a keypress (other than disabling the popup blocker).
The way that the popup blockers in IE, Firefox and Chrome work (from a high level) is by the browser (upon encountering a call to window.open) walking up the JavaScript call stack to determine if the current function is—or was called by a function that is—an event handler. In other words, it finds out if the current function is executing because the user did something that triggered a DOM event.
If so, then the popup is allowed; otherwise it is blocked. However, the question of which events qualify as "popup-allowing" vary by browser. By default in Mozilla, only change, click, dblclick, mouseup, reset, and submit qualify. (I assume IE is similar.)
Functions that are event handlers for any other type of event – such as keydown/keyup/keypress in your case – do not qualify for special popup-allowing treatment, which means your popup is blocked and is why your call to window.open returns null.
Chrome, however, does consider the keydown event eligible for allowing popups to be opened, which is why your script works in that browser.
Here's a reduced example to demonstrate how this works. This demo:
Defines a function called spawn() which calls window.open to open a popup.
Calls spawn() immediately as the page is loaded. This is blocked by all browsers since the call is made from the global scope; it is not called from an event handler.
Attaches a function to window.onkeydown which calls spawn(). If you press any key in Chrome, the popup will open because it allows popups from keydown handlers. In IE and Firefox, the popup will be blocked becuase those browsers do not allow popups from keyboard events.
Attaches an event handler to the link which calls spawn(). When you click the link, the popup will be allowed in all browsers because the call to window.open can be traced back to an event handler for a click event.
As you can now see, nothing goes on to manipulate event properties or "trick" the browser in to not knowing that there's a new window. The behavior of popups being allowed to open from link clicks is by design, the theory being that if you've clicked on something, it's likely that you want to see whatever is in the popup. However, when a call is made to window.open from a place where you've not done anything (such as the global scope), it's likely you do not have any interest in whatever [ad] is in the automatically-launching popup.
In this way, popup blockers prevent annoyances (automatically launching ads) while still allowing pages to open popups at the user's request.