detect the difference between close and refresh - javascript

I know all the easy answers concerning onbeforeunload, click and keypress. but still, the browser seems to know what is happening, therefore, somewhere that information should be available.
try it, make such a page with onbeforeunload. you'll see that whenever you refresh, the popup mentions something about reloading. yet if you go to a completely different page, the confirmbox mentions something about navigation.
is there any guru who knows this and if this is (gonna be) possible?

Related

window.open affect web page

I have a link that opens a new window using window.open. The pop up works fine, however the normal web page stops loading objects (images, scripts, ajax scripts) and sometimes the page doesn't load at all.
Here is my code:
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
Is there anything I am doing wrong?
Thanks,
Peter
First of all, please be more specific: tell us more about your browser and which version, and possible your OS. It could be more related to the browser than to the web content.
Then on to the possible problem; you start with saying "I have a link that ...".
To me that sound like you use <a href="javascript:DoSomething()">. Or perhaps <a href="#" onclick="DoSomething()">.
I tried both in some modern browsers: Chrome v37, IE v11. Both browsers did not produce what you describe:
- Chrome v37 will happily keep on loading, even if I immediately click a "window.open()"-link on top of a (huge) webpage;
- IE v11 will someshow show "false", which is strange, but still not what you got.
In some cases I also got to deal with the popup blocker.
A general tip might be to NOT USE <a href> for things like this. Behaviour seems inconsistent across browsers, also these days there are better alternatives, such as <span onclick="">...</span> and <button onclick="">...<button> or by using JQuery or other frameworks (which I do not know much about).
Although this many not be a conclusive answer, maybe this can help you experiment on your own, and think about possible causes or alternative ways of doing things.
The behaviour you describe should definitely NOT normally happen. This is confirmed by robbmj's JSFiddle, that fails to reproduce the problem. That's evidence that something is going on in the main page that is not plain vanilla page loading, or your "link opening" has something unusual to it. Apart from the syntax error (you use four parameters, not three).
Since you do not supply information on either of these points (how do you load the main page? How do you trigger the popup-opening code?), we do not even know if the problem
might be browser-related; I'd start and try to test things in IE, Chrome and Mozilla to see
whether anything changes; this might provide some useful insights.
One possibility
A very strong possibility is that your inadvertent fourth parameter goes into the window.open() "replace" parameter, which is a boolean, and triggers undefined behaviour or simply an error that stops everything. You should have things somewhat working in IE and not working at all in Firefox.
You should also be able to see whether this is the case by using Firefox and the Firebug extension, or the Web Developer Console in Chrome.
Another possibility
A more esoteric possibility is that the way you define the link might make the browser believe you've actually moved on to another page, so that there's no point in continuing loading the current page. Depending on the browser, this might have to do with how the link is defined and could be remedied by defining it some other way.
For example it could conceivably happen if you had
...
which I suspect is what led user Tomzan to ask, "is the link something like javascript:...?"
So if this is the case, try with this instead (this works for me in IE9/Chrome/FF):
link
function openPopup() {
MyWindow = window.open('player.php', 'Player', 'width=500, height=300');
// Also try the following. You won't probably like the results (it should send the
// popup window behind), but if it works, it proves we're dealing with a browser
// issue there.
// Blur and refocus
// MyWindow.blur();
// window.focus();
// Just focus
// window.focus();
return false;
}
Workaround
A possibly acceptable workaround could be to disable the link altogether (or hide it via CSS), and only reactivate/show it upon main document being ready. This sidesteps the problem, even if user experience could be somewhat worse due to a longer wait.
But if it's so likely that a user clicks on the link before waiting for the whole page to load, I'd also consider not automatically loading the rest of the page at all, and reorganize information to provide a more streamlined navigation. Or maybe distribute it on two sequential pages. Again, unfortunately you did not supply enough information to do more than guess.
As you probably know, JavaScript is single threaded. Every event is queued until there is idle time for it to be executed.
In the case of window.open, both windows must share a single context to keep it thread-safe because the opened window can access to it's parent using window.opener.
I don't know how browsers implements it, but we can guess two possibilities:
Idle time is shared between the two windows. It means if the popup does many blocking statements, it can freeze the main window's events.
Only one of the two windows can be active, which depends on which one has the focus. In that case, all events may be paused in the main window when you're using the popup.
If you want a more precise answer, I need more details about your code.
document.addEventListener("DOMContentLoaded", function () {
//whatever the code
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
}, false);
Try to wrap the code in SetTimeout
setTimeout(function () {
window.open( .. )
}, 0);
Your document should be loaded first, then popup should be open, So write your javascript code in the scope of $(document).ready().
enter code here
$(document).ready(function(){
$("#clickme").click(function(e){
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
});
});

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.

Javascript: Alert user without using an alert box

I'm trying to find an elegant way to inform a user that s/he is about to be logged out and I know that most browsers will give you some indication that a hidden tab has an alert box open. I would like to duplicate this functionality without actually showing an alert box.
I have thought about forcing the tab/window to gain focus, but that is quite obtrusive and I hate it when websites do that to me, so I'm looking for something a little more subtle.
Any ideas?
Edit/Clarification: I already have a div that pops up if they are about to be logged out. My problem is that if they are on another tab, they won't be able to see that div, so I would like some way to notify the user that something important has happened on my tab so they go check it out and see the logout notice.
The favicon idea listed below is an excellent idea, any others?
Here's an interesting way that comes to mind. When its time to be logged out, change the website's favicon dynamically. Newer browsers should be ok with it.
Look here: Changing website favicon dynamically
Some techniques I've seen:
Some sort of sound that's played (I think it's done with Flash in the case I'm thinking of, but maybe it's possible with HTML5's audio tag)
Flashing/alternating favicon
Use JavaScript to change the page title tag every 2s or so
You could create a page that informs them they will be logged out in a certain amount of time with a button that would allow them to maintain their session. Or maybe you could use a lightbox modal popup window (example here).
Why not swap out a div styled how you want to change to let them know they will be logged out soon? Then, you can simply have it as a portion of your page with all the same style and formatting?
For example, your normal page has some sort of page element with visibility:block; and then before they will be logged out, you change that to visibility:none; and change your other element (in the same place) to have visibility:block;
Does this idea make sense? You have to be able to detect when this is happening with Javascript already to alert, so instead of altering you are just swapping out display elements.
I hope this is helpful,
-Brian J. Stinar-
it probably doesn't go with what you're after but a simple modal window is probably a good idea? i know it doesn't alert the user instantly, and they won't see it unless they switch back to that tab, but it's unobtrusive and i believe most users would prefer not to have something rammed in their face!
If this notification is to be triggered by a user clicking "log out" or the likes then they will see it and it won't be as intrusive as forcing them to stop what they are doing and close the alert box.
And if it's due to time out or something similar then the user isn't overly concedrned or they would still be on that tab.
I think that this serves the best purpose in terms of usability as people don't want to be hassled or have their workflow broken by an alert shoved at them! A perfect example is Microsoft TFS which would constantly throw alerts at you when you got signed out, which got really frustrating, really quickly
so my answer is think how the user would like to be notified in the least obtrusive way :-)

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.

To detect if the user is closing the IE browser apart from onunload event, as it is triggerred when user does refresh etc [duplicate]

This question already has answers here:
Identifying Between Refresh And Close Browser Actions
(13 answers)
Closed 6 years ago.
After being through numerous forums available on the net for last 5 days, I am still not able to completely track down the browser close event. My requirement is to generate a popup message, when user tries to close the browser.
I have called my javascript function on body 'onbeforeunload' event. And I have hardcoded the conditions to check the mouse-coordinates for the red 'X' buton of browser, refresh, File-close or Alt-F4.
My code works fine when browser window is Maximized, but fails if we shrink it after a limit. Please help me, if some body has already found the solution to a similar problem.
Thank you.
Aggregated Responses of OP
------
Ok, just tell me if it is possible to detect if a user has clicked on the Refresh button of the browser. Also, Refresh can be triggered by Right-click - Refresh or Ctrl-R. My requirement is to make a variable false on Refresh. I am just able to do it on F5, but all other ways are still out of my reach. The same would be applied to Back button.
Hi ppl, Thanks for all who replied at least. I have talked to my seniors regarding this and they have now understood and have compromised with the browser menu buttons. So now my task has become easy. Now, I am using a variable and making it true by default. As, I mentioned earlier I just have to catch the onbeforeunload and popup a message when user tries to leave. The message will not popup when user is navigating to other pages, as I have made the variable as false on all the links of my page using following piece of code:
document.onclick = function() {
//To check if user is navigating from the page by clicking on a hyperlink.
if (event.srcElement.tagName == 'A')
blnShowMsg = false; //To not popup the warning message
else
blnShowMsg = true; //To popup the warning message
}
In my case still the message is shown when user does Refresh, back or goes to any link in Favorites, etc.
Thanks buddy, but I have already gone through that and didn't find much help there too. My seniors are not happy with that solution as putting a flag on every link of my application is a complicated job and they fear of breaking the application. Any other suggestions would be appreciated. Thanks once again.
Is there no one who can think of a solution here!!! where are all the experts???
The question isn't an unusual one. Yet after 5 days searching the internet you still haven't found a satisfactory answer. That in itself should be a fairly plain indicator.
What I've found on the web is there is a serious aversion to the 'no can do' answer. When something can't be done the normal response is to make no response.
Bottom line is not only can what you are trying do not be done it should not be done.
I think you need to go back to your seniors and explain to them that a Web UI is a guest hosted by a browser on a client machine. This guest status is an important one.
Would you want a guest in your home to have the power to enforce you to alert them when you want to go to the toilet? No?
Similarly the browser limits what info the guest UI is allowed to access. Even if you found a workaround for the fact that browsers aren't giving up this info voluntarily, such clever hacks are fragile and likely to be constant source of bugs.
Since its likely that the application was originally intended to be delivered via the browser before any code was cut, the fault lies with including the requirement in the first place.
All we can do sympathise with you in being asked to perform an near impossible and certainly not sensible requirement.
Add this script to your HTML:
window.onbeforeunload = function (e)
{
e = e || window.event;
var y = e.pageY || e.clientY;
if (y < 0){
return "Do You really Want to Close the window ?"
}
else {
return "Refreshing this page can result in data loss.";
}
}
In your function:
document.onclick = function()
{
//To check if user is navigating from the page by clicking on a hyperlink.
if (event.srcElement.tagName == 'A')
blnShowMsg = false; //To not popup the warning message
else
blnShowMsg = true; //To popup the warning message
}
blnShowMsg will be true for any click on your page except sometimes when the user click a link. I say sometimes because if event.srcElement.tagName doesn't work in some browser it will allways be true. And you have to add lots of cases to to allow using form controls etc... Some browsers can even automatically reload a page, and I'm not sure if onload events will run then or not.
But popping a warning about leaving the page (or similar) all the time is sure to annoy a lot of people, and they'll probably leave permanently...
If you're making for instance a online program where it's critical that something is saved before leaving, I'll say that catching the before unload event is a little too late, better to make some kind of autosave (see Gmail) and/or some kind of non-obtrusive warning when the user mouseover the navigation menues without saving.
But you can't force stupid users not to do anything stupid, on a web interface this is even more true because you have less controll: if the user want to terminate the program before saving they will find a way to do so, and they will call you and complain when the unsaved data dissapears ;P
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 postback.
I believe there was some ways to do this in some browsers (and probably not very reliably) some years ago. Because I remember those awful massive spam-popups that spawned more popups as you closed one. But that's why it's not a good idea to allow scripts to detect this, and why browsers should prevent it and most modern browsers probably does.
I was asked to do something similar for a survey invitation script; they wanted to ask the visitor if they would like to answer a survey about their website, and then the survey should pop up when they leave the site. The solution I found was to (repeatedly) explain the management that this was probably impossible, or at best very unreliable; and instead the survey should popup immediately (if the visitor agreed to take the survey) and the intro page should tell the visitor to leave this window open and go back to it after reviewing the page.
onunload and onbeforeunload are not meant for this, so will naturally be unreliable.
A better solution is to change the problem. Have the client send a heartbeat, periodically telling the server the page is still active. When the hearbeat stops, you know you can clean up the server.
You might find this interesting: https://stackoverflow.com/a/3586772/1483977
Or this: Identifying Between Refresh And Close Browser Actions
"Thanks buddy, but I have already gone through that and didn't find much help there
too. My seniors are not happy with that solution as putting a flag on evry link of my
application is a complicated job and they fear of breaking the application. Any other
suggestions would be appreciated. Thanks once again."
If you use jQuery, you can add link flags automatically. The way I would handle your problem is when the user performs the "dangerous" actions, iterate all the page links that are "dangerous" and then bind events to them.
$("#dangerbutton").click(function(){
$("a").not( safeList ).click(function()
{
var dest = $(this).attr('href');
someWarningFunction(function(){
/* Stay where we are because user opted to stay */
},function(){
/* Continue Following Link because user didn't mind */
window.location= dest;
});
return false;
});
});
This way will only fire on link clicks on your page. Users have to get used to the fact that "close window == cancel everything" logic, because many use and trust that facility.
You might have seen in many of the web form pages to warn the user before closing the page.When somebody refreshes the page, then there is a chance for loosing all filled data. In that case it is very helpful.
Page life cycle includes two events like onunload and onbeforeunload. For this case you need to bind the script function in window. Onbeforeunload so that it will be called when page is unloading.
Again this warning should not be fired when you are actually submitting the page. For that set a boolean value (e.g. shouldsubmit) to submit the page.

Categories

Resources