Different actions with onbeforeunload - javascript

I am working on a simple chat script using Ajax and want to indicate when a user leaves the page. Have read several docs and found this works:
window.onbeforeunload = leaveChat;
function leaveChat(){
... my code
return 'Dont go...';
}
Unfortunately (and logically), if they cancel the exit, my code is still executed and they are flagged as leaving even though they are still on the page? It should only execute if the confirm leaving the page. Any suggestions?
I would use onunload, but it doesn't seem to work in any of my browsers (Chrome, IE).

First, you should add the event handler using:
window.addEventListener('beforeunload', function() {
// Confirmation code here
});
window.addEventListener('unload', function() {
// fire pixel tag to exit chat on server here
// UI interactions are not possible in this event
});
For further research:
unload event reference
beforeunload event reference
Window.onunload reference

Related

.beforeunload only working on refresh

I am trying to alert users before they go to another page within the app, if there is any unsaved information. I'm following the advice from several stackoverflows to use .beforeunload
but it is only working when I refresh the page, and not if I click on a link to another page on the site. Am I misunderstanding how to use beforeunload or am I needing another event listener?
application.js
//= require forms.js
forms.js
$(window).on('beforeunload', function () {
console.log('unloading')
});
The beforeunload event works like this:
// Fires just before leaving/refreshing the page. Handler will
// be passed the event object and if a returnValue is set on the
// event, the browser will display a confirmation dialog with the
// returnValue message displayed.
window.addEventListener("beforeunload", function (evt) {
evt.returnValue = "Setting this to anything but an empty string, causes this to work!";
}, false);
See this Fiddle for an example.

in chrome extensions how to trigger an event on deactivation?

I have a chrome extension which injects some DOM event listeners through the content scripts. I want to remove those event listeners from the DOM in the event that the user deactivates the plugins, is there a method to do so?
It's an interesting question. It has to do with a concept of "orphaned" scripts. I talk at length about those in an addendum here.
Problem is, as soon as the script becomes detached from the parent extension, Chrome APIs will fail. As such, detecting this is not straightforward.
There are many possible approaches:
Maintain an open port to the background page. The port will fire an onDisconnected event in case the background page ceases to exist.
This is an event-based approach - you will be able to react immediately.
But this has an important downside: maintaining an open port will prevent an Event page from unloading. So if you use a non-persistent background page, this is not optimal.
Periodically, or better yet - in the beginning of your handlers, try to do something with Chrome API. This will fail, and you can catch the exception and assume that the extension is orphaned.
Please note that this is pretty much undefined behavior. How Chrome API reacts can change over time.
function heartbeat(success, failure) {
try {
if(chrome.runtime.getManifest()) {
success();
} else { // will return undefined in an orphaned script
failure();
}
} catch(e) { // currently doesn't happen, but may happen
failure();
}
}
function handler() {
heartbeat(
function(){ // hearbeat success
/* Do stuff */
},
function(){ // hearbeat failure
someEvent.removeListener(handler);
console.log("Goodbye, cruel world!");
}
);
}
someEvent.addListener(handler);
Finally, there is a proposal to make a special event for this situation, but it's not implemented yet.
Specifically for updates when the extension is reloaded, you can make it inject scripts into existing pages and let old scripts know they should deactivate; however, since your question is about extension being removed, it doesn't help.
With the hard part done, actual removal of event listeners depends on how you added them, but should be straightforward.
onDisabled fired when app or extension has been disabled.
chrome.management.onDisabled.addListener(function callback)
EventTarget.removeEventListener() removes the event listener previously registered.
var div = document.getElementById('div');
var listener = function (event) {
/* do something here */
};
div.addEventListener('click', listener, false);
div.removeEventListener('click', listener, false);
I think you don't need to this, since once your extension is disabled, your event listener will be removed and won't be injected.

Event to be triggered when leaving website or closes the browser

I´m trying for a while execute a JavaScript function when a user leaves web site by typing a address in the browser and hits return or the user closes the browser clicking in the x button.
I tried the unload event but I cannot get the alert.
This is what I am doing:
$(window).unload(function () {
alert("Are you sure?");
});
also
$(body).unload(function () {
alert("Are you sure?");
});
I am running out of ideas!
You can listen to beforeunload event that fires before the unload event, when the page is unloaded.
$(window).on('beforeunload', function(){
// ...
})
Some browsers (like Chrome) block alerts in unload event handlers, to prevent exactly these kind of annoying messages. Try a console.log or put a breakpoint in to find out if the handler is triggered when you don't have an alert there.
SO question on a similar line:
window.onunload is not working properly in Chrome browser. Can any one help me?
You can only pass the alert by returning a string in a beforeunload handler (HT #undefined), but I would avoid even that, because popups are generally bad, and most people will do minimum processing to work out the make-this-thing-go-away option before they actually think about the contents of the box.
The function you defined in window.onbeforeunload if it returns a string it will pop up a confirm navigation prompt with that message.
Alerts may be ignored!
window.onbeforeunload = function() {
return "All unsaved data will be lost. Are you sure?";
};
Some browsers handle the onbeforeunload differently. Recent Firefox for example will ignore your return string and just display a standard message.
$(window).bind('beforeunload', function(){
alert("Are your sure?")
});

Window.OnBeforeUnload

I am trying to create a customisation to our existing software, which launches on this event. I need to be able to catch the window.onbeforeunload again once the user has made their choice.
I have tried wrapping the functions but can't seem to be able to overwrite the one which is loaded first. Does anyone have any ideas about how I can approach this, or force the newly assigned function to overwrite the old one.
You can not cancel the unload depending on which button the user presses, and you can not invoke this event manually. It's not even a standard event. Think of the vulnerabilities that could be used for malicious purposes if the event had the capabilities you want it to have.
This is about all you can do...
window.onbeforeunload = function() {
alert("one"); // First time, choose to stay on page
window.onbeforeunload = function() {
alert("two"); // Second time
}
}

How many times is onunload triggered?

I have just been helped on a problem I have here.
var win = window.open(url, name);
win.onunload = StartLoad;
win.close();
To solve this problem completely, I wanted to know if onunload will be triggered once or every time a event occurs?
In other words, will my function startLoad run every time the child window "win" gets redirected, closed etc? Or will it do this event once and that's it?
Apologies, if this is a silly question.
Thanks all
No - this method can fire multiple times as you navigate off a page in IE6 and IE7.
This code snippet illustrates this (save as OnUnloadTest.htm):
<body>
<form id="form" action="OnUnloadTest.htm" method="post">
Click here
</form>
<script type="text/javascript">
window.onbeforeunload = beforeunload
function beforeunload() {
alert('OnUnload');
}
</script>
</body>
Basically, the event fires once for the actual anchor click, and once as the page actually posts back. I've only seen this issue when you have javascript in the href of the anchor, although if you use ASP.NET linkbuttons then be warned as this puts javascript in the href.
For most other sorts of navigation (e.g. user clicks a normal anchor, or closes the browser, or navigates away with a bookmark, etc) the event does only fire once.
It should only fire once, the first time the window unloads. Anything else would be a security hole.
If you want to make sure that your event handler only runs once you can have the handler unbind itself the first time it is invoked. This will guarantee that the callback does not run more than once:
var win = window.open(url, name);
win.onunload = function(event) {
win.onunload = function() {}; // assign a noop
return Startload.call(this, event);
};
win.close();
Some JavaScript libraries have a built-in helper for binding an event handler that you only want run once. For example, jQuery has a one() method for this purpose:
var win = window.open(url, name);
$(win).one('unload', Startload);
win.close();
Read WebKit Page Cache II – The unload Event for interesting discussion on how unload event plays with page caching feature of modern browsers.

Categories

Resources