I would like to have an animation effect which starts when people leave a page.
I use this currently:
window.onbeforeunload = function (){
alert("test");
console.log("test");
sliderIntervalId = setInterval('SlideDown()',1);
}
While the "test" is indeed logged to the console, the neither the function slideDown nor the test alert is produced...
Is this normal behavior? can we use the beforeunload function only for backend purposes?
P.S. I'm testing on chrome, that's why I had to use onbeforeUnload i.s.o onUnLoad which seems not to be supported by Chrome?
onbeforeunload can delay the page unload in only one case: When a return statement with a defined value is returned. In this case, the user gets a confirmation dialog, which offers the user an option to not leave the page.
Your desired result cannot be forced in any way. Your animation will run until the browser starts loading the next page:
[User] Navigates away to http://other.website/
[Your page] Fires `beforeunload` event
[Your page] `unload` event fires
[Browser] Received response from http://other.website/
[Browser] Leaves your page
[Browser] Starts showing content from http://other.website/
Assuming jQuery for the sake of brevity:
$('nav a').click(function (e) {
//ignore any "modified" click that usually doesn't open in the current window
if (e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.isDefaultPrevented()) {
return;
}
//where you going here?
var place = this.href;
//you're not going anywhere, buddy
e.preventDefault();
//watch me dance, first
$('.animate-me').fadeOut(1000, function afterAnimation () {
//you're free to go!
document.location = place;
});
});
Basically, you don't use onbeforeunload. One advantage is that you can keep the user as long as you want, one disadvantage is that the user won't see an animation when using a link outside nav (but you can just change the selector)
Obviously keep the animation fast, like suddenlyoslo.com do.
Jorrebor,
If your trying to have this animation fire when they leave your site or close the browser it will not work as intended. However, you can create this animation while the user travels within your site by removing the 'href' property of your links and creating animations that have a callback function that set the window.location property. Something like:
document.getElementById('home').onclick(function(){
yourAnimationFunction(function(){
window.location="example.com";
});
});
alot of work and wont be seo friendly however
I am working with onbeforeunload and What I was able to figure out is:
onbeforeunload handler is blocking the browser from destroying the current page
if you don't return anything, the popup does not appear.
So your code will be working as long as the event handler runs.
This means that timer functions are not usable. They just add to the execution queue, so anything they would do is being queued after the end of currently running handler, which is after the last point in time you were guaranteed your code is still running.
So there is only one way to stop the browser from unloading before the animation finishes:
put a blocking loop that wastes some time in the beforeunload handler
start CSS3 animation by setting an appropriate class on the element before the loop
make the loop end when the animation finishes (make the loop check the actual height of an element or something)
Oh, and yes, this is a nastiest hack of all, but I was able to find a way to stop the browser from unloading the page, right?
I would appreciate comments with ideas on what to put in the loop.
I am taking some options into account:
wasting CPU on come math on large numbers
accessing localstorage (synchronous call, IO operration)
accessing DOM (this solution already has to)
Any ideas?
Related
I have the following jQuery code in my page onload function:
$("#vid-pages").find("video").on('canplay', function() {
$(this)[0].currentTime = $(this)[0].duration / 2;
console.log($(this)[0].currentTime);
});
There are only two videos in that container, and none anywhere else on the page. When I check the console, it's continuously flooded with the time returned in that code block. What is the solution to make this trigger only once, instead of constantly?
When the current time is changed the browser needs to load more data either from cache or the network. This can trigger the canplay event. And since a time is set in the event handler you will get a never-ending loop (you can see the effect of canplay being triggered here by choosing a video, hit play then skip to the middle right after). It may depend on the browser.
This page on MDN states the following to the related canplaythrough (though not entirely the same it is reasonable to believe this also applies to canplay as shown in the media event page using Firefox):
Note: Manually setting the currentTime will eventually fire a
canplaythrough event in firefox. Other browsers might not fire this
event.
To avoid either unsubscribe from the event, or use a flag which forces exit at the second time the event is triggered.
var initialPlay = false;
$("#vid-pages").find("video").on('canplay', function() {
if (initialPlay) return;
initialPlay = true;
$(this)[0].currentTime = $(this)[0].duration / 2;
console.log($(this)[0].currentTime);
});
For unsubscribing you would need to use a non-anonymous function.
i have that problem: i need to have a variable set to false/true depending on whether the page is loaded in the current tab or in an inactive tab. so i tried to do it with the focus-event, more or less like this (it's jquery):
var hasFocus = false;
$(function() {
$(window).focus(function() {
hasFocus = true;
});
});
firefox and ie it do what i want: if the page is loaded in the active tab the event is triggered immediately, loaded in a background tab the event is only triggered when the tab gets active.
in chrome however the event does not get triggered when the page is loaded in the current active tab. does anybody know a workaround for this? i also tried events like mouseenter, hover but unfortunately they get executed on pageload in an inactive tab too... thanks in advance!
A tricky way would be this.
setInterval/setTimeout is only fired once a second at most for inactive tabs in Chrome. So, you could set an interval (or timeout) to be run after e.g. 10ms. If it only runs after a much longer time (e.g. 1 second), the page must be inactive. Otherwise, it would be run in 10ms (like you set).
I woulds suggest that you try mousemove as an event -- e.g.
var humanHasInteracted = false;
$(function() {
$(window).mousemove(function() {
humanHasInteracted = true;
});
});
alternatively use bind/unbind so that the event handler can removed when the first mousemovement is detected.
Is it possible to determine whether a user is active on the current web page or, say, focused on a different tab or window?
It seems that if you switch tabs, any JavaScript set on a timeout/interval continues running. It would be nice to be able to 'pause' the events when the user is not on the page.
Would something like attaching a mouseover event to the body work, or would that be too resource-intensive?
You can place onfocus/onblur events on the window.
There's wide support for those events on the window.
Example: http://jsfiddle.net/xaTt4/
window.onfocus = function() {
// do something when this window object gets focus.
};
window.onblur = function() {
// do something when this window object loses focus.
};
Open Web Analytics (and perhaps some other tracking tools) has action tracking
You could keep an alive variable going using mousemove events (assuming the user does not leave the mouse still on the page). When this variable (a timestamp likely) has not been updated in x seconds, you could say the page is not active and pause any script.
As long as you do not do a lot of processing in the body event handler you should be okay. It should just update the variable, and then have a script poll it at a certain interval to do the processing/checks (say every 1000ms).
Attach listeners to mousemove, keyup and scroll to the document.
I use this throttle/debounce function (which works without jQuery, even though it's a jQuery plugin if jQuery is present) to only run code in response to them once in ~250ms, so that you're not firing some code on every pixel of the mouse moving.
You can also use the visibilityState of the document:
document.addEventListener("visibilitychange", function() {
if( document.visibilityState === 'visible' ) {
// Do your thing
}
});
There is a wide acceptance of this API.
Looks like Apple has disabled the window.onbeforeunload event for iOS devices (iPhone, iPad, iPod Touch). Unfortunately I can't find any documentation as to why this event doesn't work in Mobile Safari.
Does anyone know if there's a reliable alternative to this function? Android's browser appears to support it just fine, and the Safari desktop application also supports the onbeforeunload event without issue.
I see that it's an old question, but i faced this problem recently.
I'm using window.unload and it works fine in ios browsers (although if you look at Apple documentation it seems to be deprecated and they recommend to use document.pagehide)
If you really need it, you cant just get all links, forms and DOM objects that have a handler changing the url and make those wait until you've done what you want.
For the links, you get them by getElementsByTagName, check if the href starts with anything but a # and just add your onbeforeunload function add onclick (which will be invoked before the href is looked at).
Same for the forms but with onsubmit.
And finaly, for the elements changing the href with JavaScript, you should make sure when you add the lsitener that you call your onbeforeunlaod function (or, if you use DOM0 or DOM1 listeners, you can just add some class and then use a global script that checks all elements with the class and adds it to the event listener with a closure.
But you should normaly be able to avoid the use of this event (probably using cookies to store the thing you wanted to send every x seconds and allowing to, in the worst case, have a look at it next time the user loads a page and, in the best case, be able to send an Ajax request at onbeforeunload or onunload which, even if it sends only the http headers, woudl allow you to get what you want).
Based on Xavier's answer, I devised a solution along these lines:
function doStuff() {
// here goes your logic
}
function isSafariMobile() {
return navigator && /Safari/.test(navigator.userAgent) && /iPhone|iPad/.test(navigator.userAgent)
}
function addWatcherToLinks(baseNode) {
if (!baseNode || !baseNode.querySelectorAll) { return; } // ignore comments, text, etc.
for (const link of baseNode.querySelectorAll("a")) {
link.addEventListener('click', doStuff);
}
for (const form of baseNode.querySelectorAll("form")) {
form.addEventListener('submit', doStuff);
}
}
// ...when the page loads...
// we watch the page for beforeunload to call doStuff
// Since Safari mobile does not support this, we attach a listener (watcher) to each link and form and then call doStuff.
// Also, we add such a watcher to all new incoming nodes (DOMNodeInserted).
if (isSafariMobile()) {
addWatcherToLinks(document);
window.addEventListener("DOMNodeInserted", (event) => { addWatcherToLinks(event.target); }, false);
} else {
window.addEventListener('beforeunload', doStuff);
}
This solution has some limitations. The biggest one is that it attaches itself to all forms and all links. Sometimes this might not be desired. If you need it you can skip some nodes (e.g. mark them with a particular data- attribute).
I was having the same problem. it seems safari browser in iphone triggers only focus and blur events and almost every other event is not triggered, e.g.(pagehide, pageshow, visibility change) but the good news is focus and blur event are supported and triggered on iphone, ipad & android mobiles as well.
window.addEventListener('focus', function(){
// do stuff
});
window.addEventListener('blur', function(){
// do stuff
});
hope this helps anyone.
I have a page which does quite a bit of work and I don't want the user to be able to navigate away from that page (close browser, hit back button, etc.) without getting a warning. I found that the onbeforeunload event (which I think is IE-specific, which works fine for me as the project uses lots of ActiveX) works great.
Problem is, I want the user to be able to click on a little "help" icon in the upper-right corner and pop up a help window at any time. This causes onbeforeunload to fire, even though the main window never goes anywhere and the page never unloads.
The JavaScript function that runs when the onbeforeunload event runs just puts text into event.returnValue. If I could ascertain, somehow, that the help icon is the one that was clicked then I could just not put text into event.returnValue in that situation. But how could I have the page figure that out?
Let me guess: the help "icon" is actually a link with a javascript: url? Change it to a real button, a real link, or at least put the functionality in an onclick event handler (that prevents the default behavior). Problem solved.
<!-- clicking this link will do nothing. No onbeforeunload handler triggered.
Nothing.
And you could put something in before the return false bit...
...and the onunload handler would still not get called... -->
blah1
<!-- this should also do nothing, but IE will trigger the onbeforeunload
handler -->
blah2
EDIT: My "workaround" below is complete overkill, based on my lack of understanding. Go with Shog9's answer above.
OK so while I was writing the question, I came up with a workaround which will work for now.
I put a global JavaScript variable in act as a boolean on whether or not the icon is being hovered over. Then, I attach events to the image's onmouseover and onmouseout events and write functions that will set this value. Finally, I just code in the function that handles onbeforeunload that will check this value before setting event.returnValue.
Probably not a flawless workaround but it will work for now.
on the internet you will find many people suggesting you use something like
window.onbeforeunload = null
but this does not work for me in IE6. reading up in the MSDN docs for the event object i found a reference to the event.cancelBubble property, which i thought was the solution. but thanks to Orso who pointed out that setting "event.cancelBubble=true" is useless, the way to get rid of the confirm prompt is to exclude the return statement altogether, i chose to use a boolean variable as a flag to decide whether to return something or not. in the example below i add the javascript code programattically in the code behind:
Page.ClientScript.RegisterStartupScript(typeof(String), "ConfirmClose", #" <script> window.onbeforeunload = confirmExit; function confirmExit() { if(postback == false) return ""Please don't leave this page without clicking the 'Save Changes' or 'Discard Changes' buttons.""; } </script>");
then the help button contains the following aspx markup:
OnClientClick="postback=true;return true;
this sets the 'postback' variable to true, which gets picked up in the confirmExit() function, having the effect of cancelling the event.
hope you find this useful. it is tested and works in IE6 and FF 1.5.0.2.
I have a method that is a bit clunky but it will work in most instances.
Create a "Holding" popup page containing a FRAMESET with one, 100% single FRAME and place the normal onUnload and onbeforeUnload event handlers in the HEAD.
<html>
<head>
<script language="Javascript" type="text/javascript">
window.onbeforeunload = exitCheck;
window.onunload = onCloseDoSomething;
function onCloseDoSomething()
{
alert("This is executed at unload");
}
function exitCheck(evt)
{
return "Any string here."}
</script>
</head>
<frameset rows="100%">
<FRAME name="main" src="http://www.yourDomain.com/yourActualPage.aspx">
</frameset>
<body>
</body>
</html>
Using this method you are free to use the actual page you want to see, post back and click hyperlinks without the outer frame onUnload or onbeforeUnload event being fired.
If the outer frame is refreshed or actually closed the events will fire.
Like i said, not full-proof but will get round the firing of the event on every click or postback.