Reloading a browser window when user switches away - javascript

I'm writing a quiz site for a client and the entrant gets 30 seconds to answer each question on the page. If they switch to another tab or the window blurs, I want that window to load an error page. This is based off jQuery code I used in 2015 which used to work fine, now when I test it, the "Leave site?" prompt pops up infinitely.
The old code used to be:
$(window).blur(function() {
window.location = "<?=$server_url?>quiz_error.php";
});
I'm guessing the alert prompt itself is triggering another blur event and we are stuck in an infinite loop.
Is there a way to have this blur only trigger once so I can load the error page?
I tried
$(window).blur(function(e) {
e.preventDefault();
window.location = "<?=$server_url?>quiz_error.php";
});
but this didn't work either.
Many thanks :)

Related

Chrome executing all JS again on browser back button

I am developing a web application. And I wrote some JS script to be executed on document ready. But in chrome when we click on back button and go back to previous page it is executing all the js script again. But when I use same on firefox it do not execute the JS.
I have an accordion on a page and when user open any accordion and go on one of the link under the accordion and after that if again clicks the back button on the accordion page chrome is closing all the accordions as I have written the script to close all these on document ready. But firefox do not close.
Is there any way to fix this with javascript? So that I can put any condition like if(history.forward.length < 1){ do this....}
You can use the pageshow event to guarantee you always detect navigation to a particular page, regardless of whether the user presses the back/forward button or selects a link, and regardless of which browser is being used.
Then you can perform checks regarding the state of UI and perform logic as required (i.e. modify UI, prevent execution of additional JS).
window.addEventListener('pageshow', function(event) {
// check state of UI, etc.
});
The solution that came to my mind is using sessionStorage to know if it is a first time loading or not. Or even better, you can keep state of your accordions in session storage so it always be the way the user want.
In my case, the iframe was a hidden iframe (width and height zero).
This iframe is just an workaround from legacy system, developed 12 years ago. But still using nowadays on current application.
To solve it, i just redirected the page loaded into iframe to the blank page.
Example:
page_loaded_into_iframe.php
<?php
//do the php stuffs
?>
<script>
alert("hello world");
location.href = "about:blank"; // here, where the the magic happens!
</script>
Once pressed the "back button", the browser will reload a blank page.
Be aware that this might be not applicable if your case is not similar to mine.
In the Chrome Extension you can use the function:
chrome.webNavigation.onCommitted.addListener(function callback)
and in the callback function you may take a look to the arguments:
transitionType + transitionQualifiers
to look for:
"forward_back" The user used the Forward or Back button to initiate the navigation.
For deatils see chrome.webNavigation
Of course, this event can be communicated to the content script with the usual message model (refer to: Message Passing

reload page on mobile browser javascript

I'm trying to reload my page every time the user puts my page in focus again or opens their browser. My code works, if the user is in the browser and changing pages, but it doesn't work if the user exit the browser (without actually shutting it completely down) and then opens the browser again, where my page would be the first site they see. I am testing this on chrome for android. Is there another event I need to listen for?
I am looking for a method to reload on all browsers as soon as the user enter my page, no matter what state it was in before - mobile browsers are especially important.
Code:
<script type="text/javascript">
onload = function () {
onfocus = function () {
onfocus = function () {}
location.reload (true)
}
}
</script>
This is a pretty crazy idea to reload the page all the time in full, your users will hate you. If you are going to do it, just do partial updates to the page.
Anyway, to answer the question, check the PageVisibility API(Chrome) or the specs. This event fires when the page is visible to the user either by bringing the app into focus or by changing tabs.

How do I attach a Javascript event to the mobile Safari back button?

I need to show a confirm dialog box when the user clicks the back button in mobile Safari. I have a long application, and I want to alert users that their application has not been filled out/completed before they leave the page. I have everything set up for when the user clicks a link and tries to leave the page, but I can not for the life of me figure out how to attach an event to the browser's back button. onbeforeunload does not work in iOS. Any tips would be much appreciated.
NOTE: I realize alert boxes are the spawn of satan, but that's what I was told to do.
You can check the persisted property of the onpageshow event. It is set to false on initial page load. When page is loaded from bfcache (user navigates back with back button) it is set to true.
window.onpageshow = function(event) {
if (event.persisted) {
alert("From back / forward cache.");
}
};
For some reason jQuery does not have this property in the event. You can find it from original event though.
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
alert("From back / forward cache.");
}
};
In desktop browsers like Chrome you can intercept the leaving of a page and show a message.
And you can't do anything, except for showing the message. The browser is doing the rest, for obvious reasons.
Dunno if this also works on iOS.
window.onbeforeunload = function () {
return 'do you really wanna do that?'
}
http://jsfiddle.net/JAAZ5/
Control over the back button has never been allowed in any browser. I suspect mobile Safari is no different.

Difference between onbeforeunload and onunload

What are the differences between onbeforeunload and onunload ?
Also I have a specific question related to it's use on the iPad...I have a page (myPage.html) where I am trying to show an alert when the page is closed (i.e. X is pressed to close the tab on iPad)
Now I tried using both window.onunload and window.onbeforeunload
Below are my findings on the iPad;
Using window.onunload , I am able to get an alert when user navigates to a different page from myPage.html (either by clicking on some link or doing a Google search while on myPage.html) . However nothing happens when the tab is closed from the minimized view (X)
Using window.onbeforeunload, I neither get an alert even if the user navigates to a different page from myPage.html OR if he closes the tab (X) from the minimized view.
I wanted to know if there is any alternate way to fix this issue ?
Thank you.
onunload is responsible for executing an instruction when the page is closed. It also causes issue with IE and AJAX.
onbeforeunload is more efficient because it does not run in competition with the actual closing of the window and is triggered before onunload
I know Opera used to not acknowledge onbeforeunload - not sure if they've fixed that, but I always register the listener for both to be safe:
window.onunload = window.onbeforeunload = (function(){...
Adding with AlienWebguy's ans, to avoid dual calls at the browsers that support both events,
var onBeforeUnLoadEvent = false;
window.onunload = window.onbeforeunload= function(){
if(!onBeforeUnLoadEvent){
onBeforeUnLoadEvent = true;
//your code here
}
};
onbeforeunload:
Called before unloading begins
MDN tells me you can cancel the closing of the page using event.preventDefault();
or by returning a non-void value (ie a value != 0), the page will pop up a confirmation dialog that allows the user to choose to cancel the close
MDN also says Opera 12 and up support onbeforeunload - looks like its supported it for a while now
onunload:
Called after unloading has begun, but before any resource deallocation (its not clear to me what exactly is done during this period)
Its too late to cancel the page close at this point
The only reason I can think of why you would want to use onunload over onbeforeunload would be where your onunload code could take some significant time, and don't want the user to see a window that hangs while closing.
One significant difference (other than cancelability) between the onbeforeunload and onunload is that the former is triggered for download links and the latter is not. Example: download will trigger the onbeforeunload handler, but not the onunload.

JavaScript To Get An Alert To Redirect When Closing The Browser Window

I'm trying to get this JavaScript to work properly. My intention is, when a user is trying to close the site page to get an alert saying "stay on current page or close" If they hit 'ok' I want it to close, if they hit 'cancel' i want it to redirect to another page. The problem is, when they try to go to another page on the same site, it gives them that popup. I want it to show only when closing, not when leaving the page to another page. I'm not sure if that's possible, I do appreciate your help and comments.
window.onbeforeunload = fget;
function yPop(url) {
var found = 1;
window.onbeforeunload = '';
window.location = url;
return false;
}
function fget() {
alert("Thank you for visiting our website, you are welcome any time! \n\n");
window.location = "http://NewLink.com";
return "\n________________________\n\n PRESS 'CANCEL' To Stay On The Current Page \n\n________________________\n";
}
The problem is, when they try to go to another page on the same site, it gives them that popup. I want it to show only when closing
Don't do this.
You can't detect closing only, but you can tell the difference between leaving by clicking on an internal link and other kinds of leaving, including external links, back button, closing and choosing/typing a new URL. In a script after the page has loaded, set the onbeforeunload event, then scan over all the document.links and test their .host against the current location.host. If they match, it's an internal link. In this case add an onclick event to them that removes the onbeforeunload event before returning true, allowing the link to operate normally without a warning.
Seriously, don't do this. It is incredibly irritating, arrogant and useless. Webmasters who employ leaving-pester scripts are condemned to the the fourth circle of internet hell, where they must spend the rest of eternity making stylesheets work on Netscape 4 using only ed, a worn toothbrush and a < layer>-tag.
you should use the window onbeforeunload Event.
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
https://developer.mozilla.org/en/DOM/window.onbeforeunload
for jquery users :
$(window).unload( function () { alert("Bye now!"); } );
You may want to consider building a "You're about to leave this site" page instead.
The idea is that you wrap URLs on the page that aren't on your site to point to that page, letting the visitor know they're about to leave, and giving them a chance to go back, or proceed.
It's gentler than an unexpected modal dialog, it lets you format your messaging better, and it ultimately gives your users the exact same choice.

Categories