Inconsistency with beforeUnload across different browsers - javascript

I'm attempting to run a function (that sends some fetch calls to an API) inside of a "beforeunload" event handler and the results are mixed. With Chrome it successfully runs my function if the user reloads the page or clicks a link for a different webpage, but it doesn't work if they close the tab. In Firefox the function only runs if they close the tab, but not in any other scenario. When I debug the beforeunload handler in the browser I can see the event handler clearly is triggered but the function inside doesn't always run. I suspect the function I'm trying to feed being async is part of the issue but I don't know why the results would be so inconsistent?
This is how I'm currently writing the event handler
window.addEventListener('beforeunload', async function(evt){
await exitChat();
});
I've also tried not using async/await. Let me know if seeing the exitChat() function code would help or anything else.
Edit: After a bit more debugging I can confirm that the issue, with Chrome at least, is that when the window is closed it can't make it through the entire exitChat() function in time before the page closes. So is there a way to force a delay in the unloading process?

Related

Chrome Extension - how do I capture all runtime exceptions

I'm working on a Chrome extension which has a background script (or event script) which runs continuously and detects if certain web pages are visited in any tab and then does some processing.
I noticed that the script randomly stops working every now and then, but starts again if I restart the browser or inspect the console for the background script.
I know how to store data in chrome.storage.local and I want to be able to detect and make an entry everytime a runtime error is thrown, is this possible? i.e. a script wide catch block?
I saw this post which explains how to handle runtime errors, but this only works within a single callback function. I want to be able to do this for the whole script.
You are probably hitting the idle unload that Event pages use (since you say inspecting works - that wakes it up).
It was your choice to put in "persistent": false and it comes with consequences.
If you rely on any state variables, they will be lost when the page is unloaded. If you must keep any state at all, do it in chrome.storage.local.
Another common mistake is not re-registering all event listeners every time the script runs. The unload-but-remember-listeners mechanism depends on it; if an event is triggered, the following happens:
Check it there was any listener registered for the event. If not, do nothing.
If there was, the listener itself no longer exists (JS context is unloaded). Execute the page to reconstruct the context.
After the page stops executing (disregarding async code, Chrome won't wait), pick the listener registered in this run that matches the event and execute it.
So if you, say, registered a listener in a codepath that's not executed every time you run the script (e.g. not in a top-level statement but conditionally or asynchronously), then after waking up the script won't have that listener enabled and the event will be dropped:
/* Chrome wakes up your page */
chrome.storage.local.get("option", function(data) {
if(data.option) {
// Asynchronous
chrome.someAPI.onSomeEvent.addListener(function() {
// This will not be handled after unload
});
}
});
// Synchronous
chrome.someAPI.onSomeEvent.addListener(function() {
// This will be handled after unload
chrome.storage.local.get("option", function(data) {
if(data.option) {
// Do stuff
});
}
});
/* At this point, Chrome triggers the event,
and if there are no listeners (re)registered it's lost */
So put any conditional/async processing inside the listeners.
There are also other reasons why it can stop working, but it's impossible to tell without seeing your code.

AngularJS: How to open a file in a new tab?

LIVE DEMO
Given a URI of a file, I'd like to open it in a new tab (not a new window).
It looks like it is not possible to use $window.open(uri, '_blank').
So, I tried the following trick:
var link = angular.element('');
angular.element(document.body).append(link);
link[0].click();
link.remove();
and it works.
But, if I put exactly the same code in a promise callback, it doesn't work anymore (it opens the file in a new window instead).
Any idea what's going on here?
PLAYGROUND HERE
From your code/content, you can't force the browser to open a new tab (rather than a new window, or vice-versa). It's up to the browser settings to force it one way or another.
Anything else would be a security risk.
Let us understand fundamental how pop up blocker work.
If user trigger the function to open a new url, then pop up blocker will allow it(it should applied to any modern browser - at least firefox, chrome)
If not from user (like javascript function in background, promise or any other function trigger not from user), browser will block unless user whitelist the site manually.
This is not working.
function openInNewTab() {
window.open('http://stackoverflow.com','_blank');
}
openInNewTab();//fail
This is working
<h1><button onclick="openInNewTab()">Open In New Tab - working</button></h1>
I created simple plunkr version - http://plnkr.co/edit/QqsEzMtG5oawZsQq0XBV?p=preview
So, to answer your question. It is impossible unless user authorize it (user trigger it or white listed the site).
Quote from firefox -
Pop-up windows, or pop-ups, are windows that appear automatically
without your permission.
https://support.mozilla.org/en-US/kb/pop-blocker-settings-exceptions-troubleshooting
*Open in new tab / new windows not make any difference. Pop up blocker will still always block. It doesn't means that browser will allow if open in new tab. It is just coincidentally for certain browser default the settings in that manner.
Workaround
You can ask user explicitly to trigger the function to open in new tab after the background execution.
You can display message in UI to ask user to open the url.
Example - http://plnkr.co/edit/iyNzpg64DtsrijAGbHlT?p=preview
You can only open new windows inside click event handlers fired by the user.
The reason for this is usability.
I'm not sure if all browsers have this behavior but some browsers do not allow scripts to open windows without the user being noticed. Imagine when you visit a web page and suddenly, the web page opens several windows => it's annoying.
See this DEMO (tested with my Chrome and Firefox), even we trigger click event by script, the browser still blocks the popup.
$("#test").click(function(){
openInNewTab();
});
$("#test").click();
You cannot open a new window inside your ajax success callback because your ajax success is run in another cycle after the click event handler has finished its execution.
See this link for a workaround
if I put exactly the same code in a promise callback, it doesn't work
anymore (it opens the file in a new window instead).
I'm surprised that you're still able to open a new window. But this problem really has a lot of things to do with click events fired by the user.
Your problem is two-fold, and both folds tread on uncertain territory.
In the old days of browsers, window.open did exactly that – open a new window. That's because the concept of tabs hadn't been invented yet. When tabs were introduced, they were treated exactly like windows to improve compatibility, and that tradition continues to this day. That, and the fact that window.open was only standardized very recently, means that JavaScript cannot distinguish between windows and tabs.
There is no "normal" way to specify whether a link should open in a new tab or not. You can use the following hack, though: specify a custom window size to the open call (via the third argument), like so:
window.open('http://example.com', '', 'width=' + screen.width);
This will cause almost all browsers to open a separate window because tabs cannot have custom sizes.
In JavaScript, there are trusted events and untrusted events. Trusted events are, for example, legitimate clicks on a link by the user, whereas an untrusted event would be a manual click() call on a link.
Only trusted event handlers may open new windows/tabs. This is to prevent client-side attacks that crash the browser or confuse a user by rapidly opening a hundred tabs on mouseover or something similar.
Your second example doesn't work because the popup blocker blocks the untrusted event that you triggered via the click(). Although it was caused by a real click, the asynchronous call in-between severs the link to trustedness.
working version
$http.get('https://api.github.com/users/angular').then(openInNewTab());
EDIT----------------
Do not know why but a click() method called from a callback function acts differently than calling it straight.
You can see it here with a set interval example.
That is why I had call the function directly rather than going through a callback.
see it with timer callback
or you can use $window service please see here : http://plnkr.co/edit/8egebfFj4T3LwM0Kd64s?p=preview
angular.module("Demo", []).controller("DemoCtrl", function($scope, $http, $window) {
$scope.uri = 'http://martinfowler.com/ieeeSoftware/whenType.pdf';
function openInNewTab() {
var link = angular.element('');
angular.element(document.body).append(link);
link[0].click();
link.remove();
}
$scope.works = openInNewTab;
$scope.doesntWork = function() {
$http.get('https://api.github.com/users/angular').then($window.open($scope.uri));
};
});
For us the following worked well: http://blog-it.hypoport.de/2014/08/19/how-to-open-async-calls-in-a-new-tab-instead-of-new-window-within-an-angularjs-app/
In short: We remember the reference to the new window and changing the location afterwards.

Waiting event before closing window using onbeforeunload

Context :
I have developped an application which require authentification. This application uses events for dialoging with a server. When the server answer, some events are send to the client (UI).
Problem :
When the user close the page, it is necessary to make a logout on the server. With my architecture, it's easy to call a method which perform this logout. But i would like that the user show the logout progress before closing the webpage. In fact, i would like to close the webpage only when a specific event (for example : disconnection_success), is well received.
Moreover, it's verry important to not launcg another webpage because event is received on the first webpage when the logout is successfull. (Because dialog is done throw XMLHttpRequest)
Test :
I already do some test using onbeforeunload but it seems that is difficult to customize the popup.
Do you have some ideas to resolve the problem ?
BR
There are some issues with this, but you're on the right track. You're right in that you should use onbeforeunload because it is the only event that you can have triggered upon the closing of the browser window. (I know you can use onunload but at that point you have no time to do anything.) The issue here is how much code do you want to execute. The onbeforeunload doesn't allow you much time before it starts to unload the page.
BTW, there are two different scenarios with onbeforeunload:
If you return a string inside the onbeforeunload event, it creates the pop-up that you were referring to. The issue here is that with the pop-up, you won't have enough time to execute code
The other option is not returning anything. Instead, call your logout methods. This should give your code enough time to execute before closing
I actually had a question very similar to this and ended up solving it myself: How to logout during onbeforeunload/onunload using Javascript
In your question you state that you want to have a progress bar displayed when they log-out. This is impossible to do when the user closes the browser. At the moment they close their window, you have lost all control, except for in the onbeforeunload (and onunload but don't use this), and that is why your code needs to be executed there. With that being said, you could anchor your logout button (I'm assuming you have one on your application) and have it display the progress bar.
Just think about what could happen if you actually did have that kind of control - where you could pop up windows and progress bars when the user is trying to close their browser window. You could pop up anything and restrict the user from having any reliable functionality. That is why it was programmed that the onbeforeunload (and unload) events are the only ones possible to access the closing of a browser. These events have some pretty strict guidelines to them that prevent any kind of possible mis-use. I understand the problem you're having, I was there and it stinks, but I think that is your only option if you were going to use onbeforeunload.

Preventing web browser from closing until AJAX response is returned [duplicate]

This question already has answers here:
JavaScript, browsers, window close - send an AJAX request or run a script on window closing
(9 answers)
Closed 6 years ago.
I've got a game that runs in the web browser (as a plugin) and what I'm trying to do is:
Detect if the user has decided to close the browser (Alt+F4, hitting the 'X' button etc)
Prevent the browser from closing whilst we fire a call to our web services to log that the user has closed the browser
Once we receive the response from the web services, release the lock and allow the browser to close as requested.
The main reason we want to do this is we're having some concurrency problems and going through our logs we want to isolate people logging out / closing the browser from genuine instances where the plugin has crashed.
I looked into doing this with JQuery (for X-Browser compatability - Opera won't work but we don't have any users on Opera anyway thankfully):
$(window).bind('beforeunload', function(e) {
e.preventDefault();
// make AJAX call
});
The problem is that this displays a confirmation dialog to the user ('Are you sure you want to leave this page') which the user might confirm before the AJAX call is sent.
So the question is, is there a way of preventing the browser from closing until the response is received? Also 'beforeunload' fires when the page is changed as well - is there a way of distinguishing clicking on a link from actually clicking close?
Grateful for any help wrt to this!
Its tricky business to avoid the browser window from beeing closed. Actually, there is no way to do that, beside returning a non-undefined value from the onbeforeunload event, like you described.
There is one possible suggestion I can make, that is creating a synchronized ajax request within the onbeforeunload event. For instance
window.onbeforeunload = function() {
$.ajax({
url: '/foo',
type: 'GET',
async: false,
timeout: 4000
});
};
In theory, this will block the browser for a maximum of 4 seconds. In reality, browsers will treat this differently. For instance, Firefox (I tested it on 9), will indeed not close the window immediately, but it also does not respect the timeout value there. I guess there is an internal maximum of like 2 seconds before the request is canceled and the window/tab gets closed. However, that should be enough in most cases I guess.
Your other question (how to distinguish between clicking a link), is fairly simple. As described above, onbeforeunload looks what is getting returned from its event handlers. So lets assume we have a variable which is global for our application, we could do something like
var globalIndicator = true;
// ... lots of code
window.onbeforeunload = function() {
return globalIndicator;
};
At this point, we would always receive a confirmation dialog when the window/tab is about to get closed. If we want to avoid that for any anchor-click, we could patch it like
$( 'a[href^=http]' ).on('click', function() {
globalIndicator = undefined;
});
As for the first part of your question, there is no reliable way of preventing the browser from closing other than using window.onbeforeunload. The browser is there to serve the user and if the user chooses to close his browser then it will do so.
For your second question, it is reasonably easy to distinguish a click on a link from other events triggering an onbeforeunload event by jQuery:
$('a').click(function(e) {...});
You could use this, for example, to make sure a click will not trigger unbeforeunload:
$('a').click(function(e) {window.onbeforeunload = null});
You can use below code to prevent the browser from getting closed:-
window.onbeforeunload = function() {
//Your code goes here.
return "";
}
Now when user closes the browser then he gets the confirmation dialogue because of return ""; & waits for user's confirmation & this waiting time makes the request to reach the server.
I'm pretty sure that what you want isn't possible using JavaScript. But since you have a browser plugin, shouldn't you be able to check whether your plugin object was cleaned up correctly? I'm not sure if you're using ActiveX, NPAPI or something like Firebreath, but these frameworks all have lifecycle methods that will be called on your plugin in the event of a normal shutdown, so you should be able to write something to the logs at this point. If the plugin crashes, these won't be called.

JavaScript + onunload event

I want to fire onunload event to do some clean up operations, I have multiple tabs(Navbar) showing multiple links to different web pages,my problem is that even when I'm in some other page my unload function which is in tag of some other jsp is fired. Please help to resove this, I want unload function to be called when user closes browser in that page.
I'm not sure how you got the onunload event to work....The problem I've found with using the onunload event is that it is fired after the page has been unloaded. This means that no more JavaScript can be executed because the page has been unloaded.
You should be looking into using the onbeforeunload event.
This event is a little unique because if the function that handles this event returns anything a pop up is displayed asking the user if they would like to continue with the operation. So, in your case make sure that your function doesn't return anything. The other thing to note about the onbeforeunload event is that, at this time, Opera does not support it (Safari, FireFox, and Internet Explorer do though).
Both the onbeforeunload and onunload events are executed every time the page is unloaded. If a control on your page submits the page to the server code, the page is unloaded and the JavaScript is executed.
If you don't want the JavaScript to be executed when a control on your page is submitting it to the server you have to implement something that checks to see whether or not your code should be executed.
This is simple, add a JavaScript boolean to the page and a function that set's this boolean to true. Make sure that every element in your page that posts back to your server code sets this boolean to true before it submits the page. Check this boolean in your onbeforeunload event to see if your cleanup code should be executed.
Hope this helps,
-Frinny
It seems that the unload function has been created in a global scope. Try placing that function only on the page you want to act.
You have a frameset page? And you want to be notified when they navigate away from the frameset? Add an onbeforeunload on the frameset. I don't know what you mean by clean up, but you can't send XHRs during unload safely across browsers

Categories

Resources