Pause the user exiting a page - javascript

Using JavaScript (and/or jQuery), Is it possible to pause the user from exiting a page for a set amount of time without showing an alert/confirmation?
(Say the user clicks on a different page or closes the window, a timer should start for three seconds [during which time something happens] and then the next page is loaded or the window closes.)

No, it is impossible in modern browsers.
(Moreover, think of how annoying that would be if every popup did that)
The closest you can do is show the dialog using onbeforeunload but you have asked to avoid this.
But why would you want to do that?
Worth mentioning, that this is a magical time. You might want to report something to the server but you suddenly can't because the user is leaving. This is one of those times things that are usually considered bad practice like synchronous ajax might make sense.

No. This is not possible. At best you can implement an onbeforeunload handler but your options at this point are very limited (you can certainly not 'wait 3 seconds').
Browsers will try to protect the user so this is behavior that browsers enforce and they have incentive to enforce it.

This works in chrome and firefox:
window.onbeforeunload = function() {
var now = new Date();
while( new Date() - now < 3000 );
};
It will also drain battery, so you are killing 2 birds with one stone.

Related

Emulate Javascript 'alert' blocking nature

Is it possible to create a custom modal message which 'blocks' the execution of the script until a user input?
For example, how can you achieve this without using the native window alert / prompt functions?
setInterval(function(){
alert('Click OK to Continue'); // timing stops until user hits ok
},4000);
I know you could have your custom dialog invoke a callback function on user input, but I'm interested in being able to force this blocking behaviour
Is it possible to create a custom modal message which 'blocks' the execution of the script until a user input?
No. There is no way to block either execution or user interaction as effectively as a native popup (since with custom popups the user is always technically capable of using developer tools to get out of it).
However, as pst says in the comments on the question, asynchronous lightboxes are not onerous, and are almost as effective at blocking user interaction as popups, so I recommend finding a library that provides lightboxes you like and running with that.
For example, how can you achieve this without using the native window alert / prompt functions?
You can't use that code to do what you say it will even with native window alert / prompt functions (see this fiddle - wait 4 seconds before closing popup). You'd need the following:
function timeoutFunction() {
alert('Click OK to Continue'); // timing ACTUALLY stops until user hits ok
setTimeout(timeoutFunction, 4000);
}
setTimeout(timeoutFunction,4000);
Which is something that you can't implement (precisely - see above on lightboxes) without native popups.
Even while(true) loops won't generally block as well as a popup - firefox at least has a "stop script" message that pops up after it's been going too long, and I'm fairly sure other major browsers do too.
No, you can't (at least not in a browser). Javascript APIs are mostly async. alert/prompt are exceptions. However, it's not very hard to work with async prompts and callbacks.
A bit old, but in case it helps, I've found my solution with this:
var answer = confirm("are you sure?");
if(!answer)return;

How can I delay leaving a page via javascript?

I'm trying to get add a delay of 1000ms before a person leaved the page. I'm using the beforeunload event to start a jquery animation and would like it to finish before the page leaves.
I'm not concerned with older browsers, IE9, latest safari, chrome and FF4 are all i'm interested in.
Edit: Well I was hoping to implement it when just navigating internal pages. Sure I can make all my internal links a javascript call, but I would have preferred a less brute force method.
Also, I'm not stopping people from leaving the page, not even making them wait a huge long time, 1 second for a fade out? Thats no worse than every game I play fading out when I select quit.
Now had I asked how do I prevent a person from leaving a page, then yes all the "don't do it" would have been deserved.
Firstly, if people want to leave your page, don't put any barriers or difficulties in leaving it. Just let them.
Konerak said it well...
Using a blocking action is acceptable when the user is about to lose data by leaving the page, but using them for animations and gimmicks will quickly annoy your users.
Secondly, you can only prevent automatic closing with a blocking action, such as an alert() or prompt(), which temporary blocks the browser's viewport, waiting for user response.
jsFiddle.
Well I was hoping to implement it when just navigating internal pages.
I know it’s four years later now, but I wanted to point out that, within the bounds you’ve described, you can do this.
$(document).on("click", "a", function (e) {// Listen for all link click events on the page (assuming other scripts don’t stop them from bubbling all the way up)
// Stop the link from being followed.
e.preventDefault();
// Grab the link element that was clicked
var linkClicked = e.target;
// I'm using setTimeout to just delay things here, but you would do your animation and then call a function like this when it’s done
window.setTimeout(function () {
// Simulate navigation
window.location = linkClicked.href;
}, 1000);
return false;
});
It’s still inadvisable:
I suspect it would get annoying to users pretty quickly
Without additional code, this would prevent users from command/control-clicking to open links in a new tab.
8 years later and I'm about to code this for my own website, specifically as a fade between pages. But I'm only going to do this for navigating between pages within my site, and I'm not going to use window.onbeforeunload or window.onclick. I attach a click event handler to specific "buttons" on each page. pointer-events is even disabled for other elements, so the event's element scope is very limited. The code is a switch() statement with cases for each "button". Each button navigates to a specific page within the site.
I don't think this is bad web page or web site behavior. A 1 second delay when transitioning between pages is not going to annoy users. I think you might be able to get 2 seconds or more out of it, if you include the time it takes to load the destination page, which can also fade in gradually in as it loads data.
It's visually elegant, especially compared to typical news/info sites with flex layouts that shift all over the page while they load. Those pages spend 2 or more seconds shifting stuff around before you can read anything.
My site is already filled with CSS and SVG animations, so adding this to the internal page navigation is no sweat for this project. If you limit the element scope of the user events and you make the delays small, this is good behavior, not bad behavior, IMO. Visual elegance has value.
EDIT- As I get into it, I see that for one group of similar pages I can achieve better cross-fading between them by consolidating them into one page. That way I can truly cross-fade between each sub-page instead of fading out one page then fading in another.

Ways to detect CTRL-N or when a user opens a new window

How can we detect when a user opens a new window. The user is already authenticated and we make heavy use of sessions.
We were trying to avoid Ctrl+N javascript hooks but maybe that is an option.
I am assuming the request is the exact same URL...with Ctrl+N?
We were trying to avoid ctrl-n javascript hooks
Forget it. Whilst you could in theory try to catch keypress events for ‘n’ with the Control key modifier, there are any number of other ways to open a new window or tab which may be more likely to be used, and you won't be able to catch. File->New Window/Tab, middle click or shift-click link, middle click back/forward buttons, right-click-open-in-new-window, open bookmark in new tab, double-click browser icon...
The user is already authenticated and we make heavy use of sessions.
That shouldn't be a problem in itself. I guess what you mean is that your application is dumping all sorts of page-specific data in the session that it shouldn't have, and now you find the application breaks when you have more than one window open on it? Well, commiserations and happy rewriting.
In the meantime about all you can do is tell the user “please don't try to open two browser windows on the same application”. There are potential ways you can make JavaScript on one page notice that JavaScript is running on another page in the same domain at the same time, generally involving using document.cookie as a inter-page communications conduit. But that's also a bit fragile.
If opening a new window causes a problem in your application, then you should fix the application code to handle it instead of trying to apply an inconsistent and unreliable client-side "bandage". That's my opinion.
Why?
And anyway you can't detect it. User can open new window not only with Ctrl+N but also with File->New Window.
You could possibly put a window count into the session and increment it on window.onload and decrement it on window.onunload.
Imagine me tutting, sucking air through my teeth and going "better you than me, guvna" if you use that, though.
What I have done to solve this issue is when the user authenticates set the window name on valid login.
<script>
window.name = 'oneWindow';
</script>
And then on the master page do a javascript check:
<script>
if (window.history.length == 0 || window.name != 'oneWindow')
//history length to see if it's a new tab or opened in a new window 0 for IE, 1 for FF
//window name to see if it's a CTRL + N new window
</script>
If the check is true then hide/remove the main content of the page and show a message stating they are doing something unsupported.
This works when your login page is not tied into the master page.
If you do not have a master page then I would suggest putting the check on all your pages.
Yes and no,
You'll always see it if a control has focus, else the event is sent directly to the browser and the code on the page never hear about it.
In my experience you can't hijack the browser's shortcut, your mileage may vary. You are likely to know it happened but the browser will do its thing (for obvious reason)
In most browsers, the effect of Ctrl-N is to open a new window at the same URL as the old one and associate it with the same sessionID.
Your best bet would be to modify the back end code if possible and allow for such things. Breaking the browser's feature is never a good thing.

javascript for new tab (CTRL+T), new window (CTRL+N)?

When flash has keyboard focus, CTRL+T (new tab) and CTRL+N (new window) are intercepted by flash.
Is there a way to pass these events through to the browser so that they work (opening new tab, opening new browser) OR is there a javascript command for these actions?
This is a long standing issue with Flash and browsers. (And I mean long - check out this eight-year-old bug on Mozilla browsers.) The problem is that Flash intercepts all input events, rather than the browser. It's sandboxed in its own environment, and doesn't pass events back to the browser.
Conceptually, this isn't necessarily a bad thing. What happens when Flash wants to listen to a ctrl + n event? Should the browser take focus away from Flash because it uses that hotkey already? It'd be a real pain for Flash developers, that is for sure.
There have been proposals on how to fix this issue that I've seen for particular browsers, but there's no catch-all solution. For example, this solution is referenced in the bug, but it obviously won't work the way you want (since the user will have to jump through quite a few hoops to get it working).
So... no, for now. Would be really neat if this problem could be fixed.
Closest you could get is to have ActionScript trigger Javascript to open a blank window to a blank URL
// We abstract it in a function here in case we want to
// change it later
function openBlankWindow()
{
window.open( '' );
}
For most people, this will launch a new window or a new tab (depending on their browser preferences) but since it is being initiated by the web page, may be subject to pop-up blockers.
There is no way to actually ask the browser to specifically do one of the two tasks you are asking about. I would be a security/annoyance nightmare if web pages had the permissions/privileges to do that.

Jquery Effect Onunload

I would like to use the jquery slideUp effect when the user navigates away from the page just to make the page look cool as it closes.
I assume that I should use the onunload event but how can I delay the page closing long enough for the effect to run to completion.
One of the options that came to mind is effectively hijacking the page closing function, storing it in some variable and then executing it once I had run my effect but I have no idea how I would do that.
Any suggestions or alternative ideas are more than welcome
what you're looking for is the onbeforeunload event.
just a warning though... it should be really quick... or your visitors are probably going to hate it no matter how cool it looks
as to preventing the page from navigating away before the animation is done, that's a bigger problem... any animation is going to rely on setTimeout/setInterval and the page won't wait for those to complete before leaving.
Doing anything but closing the window when the users ask to is breaking a contract with the user. The browser window is not yours, it's the users, and no matter how cool the effect, it will inevitably annoy most of your users.
The onbeforeunload event is very restricted in what it can do. It must return a string, which is then used to prompt the user for a confirmation about leaving the page. It won't work for cool animations.
As far as I know, the only way to stop a user from leaving a page is the onbeforeunload event, which isn't cancelable. Instead, you return a string from that method, the browser prompts the user with a Yes/No dialog, life goes on. 276660 has more info about this.
I don't think you're going to have much luck with this one.
why not, instead of making a "cool" effect when a user simple want to go away from your website (even if the user closes the browser/tab the unload event will be fired) and annoying the simple user with that ... preventing him/her to return again...
...do that "cool" effect when a user reaches your website for the first time? as a normal intro effect?
I did that as a simple idea, you can see it here: http://www.balexandre.com/jmfc
I would agree 100% with Jonathan Fingland's answer, and add this.
In IE, (I'm not sure what versions support this, I know IE6 did) you can use some propriety meta tags to achieve fades etc when leaving the page. However, this is limited in browsers (IE only), so you're stuck for cross browser use.
You may find loading new content via AJAX would give you better control of effects and transitions, as well as reducing the annoyance factor to the user which can result from trying to hijack the browser actions in such a manner.
I would look at using a form of slider as mentioned above (see for instance http://webdesignledger.com/tutorials/13-super-useful-jquery-content-slider-scripts-and-tutorials),
or simply loading content panes in response to user clicks.
The only way I've found for delaying the window to close, is using an alert. If this is an acceptable compromise for your case, it will really delay the window destruction in memory, and allow your page timers to execute (of course, if user does not close the alert popup earlier than your animations finalize).
I recently used this approach so i could call a flex method through FABridge (which would otherwise be destroyed before the flex method call finishes). I'd like to hear your comments on this.

Categories

Resources