Execute Javascript onWindowClose in IE11 - javascript

I am trying to call a JavaScript function when an IE11 tab and/or window Closes.
I am trying to do it using this code:
window.onbeforeunload = function(e) {//code to execute when forced close};
This code is triggered on window update and on navigation which for me is desirable and something I base my logic on. However, it seems as though it doesn't have time to execute when tab/window is forcefully closed.
I'm in the "fortunate" situation of only needing to support IE11 on this project so microsoft hacks are ok, though of course not a preferred choice as things as always might change in the future.

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.

How to determine that a browser tab is selected and execute code in JavaScript?

I want to have one same page open on multiple browser tabs. When I click on ONE browser tab, I want a JavaScript function to be executed ONCE, just one time! Not that that function is being executed 3 times because that one same page is opened on 3 browser tabs for example.
I have tried:
window.addEventListener("focus", () => {
console.log(document.hasFocus());
});
This works fine if your cursor is focusing on a web browser and keeps switching between tabs on that browser.
But if you first focus your cursor on something else other than that web browser (e.g. computer desktop or code IDE) and then you click on a NON-ACTIVE browser tab, the above code will be executed two times, one time by the previous active tab and another time by the new active tab you just clicked on.
That is my problem.
How can I execute JavaScript code only one time when I click on a web browser tab? Any solution besides JavaScript code is also welcome e.g. tracking pixels or input field autofocus event, just to name samples. I did not mean that tracking pixels techniques will help. I am not using jQuery. I am using VueJs.
You might want to use this ancient method and JS syntax, before you adopt it for your final coding style. Have some classic vanilla flavor. It never hurts.
document.body.onfocus = function(e){console.info(e.type)}
should work exactly as requested...
but since this behavior is somewhat tied to the BOM, some browser vendors (with idiosyncratic behaviors) might require some sort of enforced filtering, Opera comes to mind.
But it should be rock solid on all modern browsers including a bonus backward compatibility, as back as Windows 98 browser version. And\or the ancient and now probably forgoten NN 4.7. ( except for the console info event log, but that's not needed for the actual use anyway )

Can javascript detect presence of firefox electrolysis?

My question is similar to the one here How to know loaded window is Firefox Electrolysis Window
Except I'm not writing an add-on, just a script to execute on a page, so I don't think I can use the solution there.
I'd really just like to know if asynchronous scrolling is active or not. Is it possible?

GeckoFX: Script Taking Too Long dialog

I have an application set up to perform some automation using GeckoFX web browser. My application is nicely setup, everything is working fine.
The problem that I'm running into is that when Gecko loads a webpage into itself, it sometimes doesn't fire the DocumentComplete event for a long time, instead gives an error dialog box that The script is taking too long, with two buttons Continue or Stop the script (although this happens rarely, but does happen).
I can't figure out how to suppress this error/warning dialog. In case the web browser is having a script error, I want it to stop processing and fire the DocumentComplete event anyway, I have coded my application in a manner to handle partially loaded webpages. But I can't reach to this point since the application gets stuck up at the error dialog.
Any suggestions on how to suppress scripting errors like this in GeckoFX? The IE Web Browser control had a property called SuppressErrors (or something).
Thanks in advance!
There exists an about:config setting dom.max_script_run_time which controls how long a script can run before this error appears. Setting this to 0 will disable the dialog entirely.
This can be done programatically in GeckoFX:
Gecko.GeckoPreferences.User("dom.max_script_run_time") = 0;
Via: https://support.mozilla.org/en-US/kb/warning-unresponsive-script

IE9 firing onbeforeunload event when the window opens

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!)

Categories