IE9 firing onbeforeunload event when the window opens - javascript

I'm building a site using the JFileUpload applet and want to handle the closing of a page in a certain way. JSTransferCancelled is called when the applet is cancelled. The following code is what I'm using to handle these events and it works in all browsers except IE.
function JSTransferCancelled(){
bCancel=false;
$.post("cancel.php");
self.close();
}
$(window).load(function(){
$(window).bind('beforeunload',function(){
document.uploader.setEnabled(false);
if(bCancel){ document.uploader.cancel();}
});
});
I open the page with the uploader on it in a new tab from the main site and want to close it when they cancel the upload. When I open the tab in IE, however, I instantly get the alert saying The webpage you are viewing is trying to close this tab. Do you want to close this tab? [OK] [Cancel] and my uploader is both inaccessible because of the setEnabled(false) call and cancelled because of the cancel() call.
What I'm looking for is the same functionality, just in IE. I know there are many many many issues in IE with events like onbeforeunload with it triggering in response to different things, but I've checked for all of those problems in my site and haven't found anything. I haven't run into anything online that deals with the kind of problem I'm having.
I've tried wrapping the onbeforeunload function in different things such as the load function above as well as $(document).ready(), but they either give me the same problems or create new ones.

Check Microsoft's Ridiculous Documentation Then make sure none of the code you are using does anything they list as a trigger to invoke beforeunload, which includes several things that do not actually unload the page (go Microsoft!)

Related

Detect Page Refresh or Navigation in Browser

I have a web app where a parent page displaying a list of records opens up a new tab ('child') to edit a clicked-on record. I want to track who has a page open, so I can display a message if more than one person is editing a unique record. This means reporting when a page is closed. I have assigned each page a GUID to facilitate recognition of the page instance.
So javascript in the browser needs to detect several scenarios:
browser tab closed
browser refresh
browser navigation to hyperlink
browser navigation forward/back
At the moment, all of these appear to trigger the window.onbeforeunload event. However I use this event to warn of changes in the underlying data, which means the event returns the confirmation text, and there is no way of knowing in this event if the user subsequently confirms or cancels the page unload. So I can't use this event to track page closure.
According to a number of sources the window.onunload event should be triggered in all of the above scenarios (and if it was, I could use it), but testing under Chrome on Windows is only triggering this event in scenario 1 (when the tab is closed). It works fine for that.
I'm pretty surprised by the lack of information around this - surely it's a bread and butter requirement in modern sites?
Has window.onunload been deprecated lately in some scenarios, or in some scenarios in some browsers? Without a reliable hook that takes place when the page is about to be replaced with some other information, it's impossible to monitor closing of a page. Any other workarounds?
I know that the two unload events suppress blocking functions (such as alerts) in the handler. However they appear to do hit breakpoints, do a console.log and allow Ajax calls just fine. I'm pretty sure they are not being fired in events 2,3 and 4 - it's not just that my debugging is being blocked.
While there appear to be answers on SO already (most of which don't work or are deprecated), I posted this because browser events are a shifting-sands scenario as security issues evolve, so I wanted to find out where we are in 2021.
Actually, it looks as if this might be the solution: https://developers.google.com/web/updates/2018/07/page-lifecycle-api#the-unload-event
Google discourages use of the unload event because it is (a) unreliable on mobiles and (b) blocks the caching of pages. It is also advised to only add the beforeunload event just before it is used, and to remove it afterwards, because it also blocks the caching of pages (I note that this is not really practical for me, however, as I use it to guard against unintentional closing of a page after a possibly significant amount of data has been entered, and this could happen at any moment).
So as of July 2018, and still best practice as of July 2021, this would be the recommended way to detect the unloading of a page:
const terminationEvent = 'onpagehide' in self ? 'pagehide' : 'unload';
addEventListener(terminationEvent, function(event) {
// handler code here ...
}, { capture: true });
This has been tested in a small ASP NET Core project using an AJAX callback to report the page termination, and appears to work reliably in Chrome and Edge. Also works in IE11 as long as
<meta http-equiv="x-ua-compatible" content="IE=edge">
is present.

Click a link and use window.open() blocks one of the links

I'm trying to create a simple JS function that will open a new window/tab when clicking a specific button, so the user will actually open 2 windows/tabs, however no matter what I do, one of the links gets blocked by Chrome as a "popup-blocked".
I'd like to do something like this:
$(document).ready(function(){
$("a").mousedown(function(){
window.open("https://stackoverflow.com/","_blank");
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click Me!
;
But when I do this, the button link doesn't work, but the JS does.
If I change the JS and add a setTimeout() to it, the button URL goes through but the JS gets blocked.
No matter what I do, I can't get both of them to go through.
Any help would be appreciated.
Navigating to two places at once, with one in a new window, is really popular with people who want to show the user a massive advert in a new window.
Massive adverts are unpopular with users, so browsers take steps to prevent this behaviour.
Sometimes legitimate uses get caught in the crossfire. Blame the blackhat end of the advertising industry.
You'll need to find some other way to display… whatever it is you want to display… to the user that doesn't involve navigating to multiple webpages at the same time in separate windows.
The problem is caused by the mousedown() event you are using which is a part of down+up sequence to trigger the click() event of the <a> tag.
so opening a new window "breaks" the flow and browser is not tracking for the mouse-up event anymore to follow the original url.
so the solution is to attach the click() event instead without stopping propagation. this will fire the attached and original events and none of them will be blocked.
$(document).ready(function(){
$("a").click(function(){
window.open("https://stackoverflow.com/","_blank");
});
})
you can try sample on this page as stackoverflow snippet is sandboxed and is blocking popups

Vaadin onbeforeunload event

Is there any Out Of the Box Vaadin 10 (and higher) event similar to window.onbeforeunload in JavaScript?
I've tried to use onDetach() or beforeLeave(), but it only works inside UI, and when user reloads the page or closes the page it's not working.
You can use the approach described in https://vaadin.com/forum/thread/17523194/unsaved-changes-detect-page-exit-or-reload that was already suggested in a comment.
At the same time, I'd urge you to be really careful with beforeunload events since they are in some situations fired even though the user is actually not navigating away from the page.
The most common case is if the user clicks a link that starts a download. In that case the browser will fire the event immediately when the user clicks the link. Slightly later when the browser receives the response headers, it will discover that it's a download and not a new HTML page to display. The end result is then that beforeunload has been fired but the previous page is still kept running.
If you want to use the event for cleanup, then the best approach today is probably a combination of the unload event and then using the new-ish Beacon API for notifying the server that the user has actually navigated away. Integrating this into a Vaadin application will require slightly more JavaScript, but it has the benefit that it will actually work.

How do I prevent browsers from blocking the pop-up window that I've created?

I created a simple JavaScript function to display my pop-up window once it loads. But it keeps on being blocked by Firefox and Google Chrome and I have to somehow enable it on the Firefox and Chrome to display the pop-up.
Are there any alternatives for this?
I have a player on the pop-up window so I have to use a pop-up to let the player play automatically. The problem is that if I put it on the page itself, once the user clicks another page the entire page reloads and the player automatically stops for a few seconds until the whole page reloads and I have to prevent this from happening.
The general rule is that popup blockers will engage if window.open or similar is invoked from javascript that is not invoked by direct user action. That is, you can call window.open in response to a button click without getting hit by the popup blocker, but if you put the same code in a timer event it will be blocked. Depth of call chain is also a factor - some older browsers only look at the immediate caller, newer browsers can backtrack a little to see if the caller's caller was a mouse click etc. Keep it as shallow as you can to avoid the popup blockers.
Please take a look at dthorpe's answer here. It covers your question.
You could try putting the player on the original page, and using something like History.js to control page changes (you could have the main page body in one wrapper div that changes, and leave the player outside of it).
Otherwise, you could try (assuming you meant a HTML5 <video> or <audio> player) downloading the data to localStorage/cookie/[other persistent storage mechanism] and have it seek everytime you change a page.
It will be hard to stop browsers from blocking your pop up window, because any way to do so is inherently exploitable; however, if you call the function to open another window from an onclick event, you may be able to circumvent some popup blockers. Also, some popup blockers allow popups when using the https protocol, although not many have this feature, and https can be hard to implement for the average website, if you don't have physical access to the server.
One other option is to open the other page in another tab (like this w3c example; you can 'click' the link with javascript).
You might also want to look at this post, as it is somewhat similar.
I only just discovered you asked this question.
Here's the answer in full.
Basically, you can simply create the popup immediately as the user event is fired, then fill it with content (your player, for instance) as you have it available.

Open new window after a click event not working in Safari, Chrome

I'm trying to open a new window like so:
$('#wrapper').click(function() {
window.setTimeout(function() {
//alert('hi');
window.open("http://example.com", "ExternalLinks", "resizable=yes, scrollbars=yes, status=yes");
}, 1000);
});
This works in Firefox, but not in Chrome or Safari (so far, I've just tested on a Mac). The alert() works in all browsers, so there seems to be something preventing the window.open from executing in Safari/Chrome. Furthermore, if I remove the setTimeout and just call the window.open then it does work in all 3 browsers. It's almost like if the window.open is nested too far away from the click event, then it doesn't work in Safari/Chrome.
So you know, I have an all-Flash website and I'm trying to get external links to open in a new window, so I'm reading the hash tag in the URL (ex. htp://example.com/#/facebook/) and if it matches certain items, then I'm calling window.open to open a specific URL. I don't have access to the Flash source, or I would handle this there.
Any ideas?
Safari/Chrome have built-in pop-up blockers that stop this from working. The only javascript that is allowed to open a new window in Safari/Chrome is javascript directly attached to click handlers (and other direct user input handlers). In past versions people figured out some ways to cheat (like generating some other element -- a form or div -- and simulating user input with javascript), but newer versions are smarter about detecting this. I'd recommend re-configuring things so that you don't use a delayed pop-up -- that is the kind of thing that can generally be jarring to a user after all.
I got around this by checking the return value of window.open() for undefined. If that is true call alert() with a message for the user to to disable their popup blocker.
var myWin = window.open([args]);
if (myWin == undefined)
alert('Please disable your popup blocker');
Another workaround
Just open a popup with ACCEPT and CANCEL options and attach the window.open action to the ACCEPT button and it will works. It worked for me...

Categories