How to cancel browser navigation that is already in progress with JavaScript - javascript

I don't believe this is possible but thought I'd give it a shot.
As part of a project that I'm working on, there is a page on a different site that a user can navigate to via a standard anchor link. The destination page is sometimes rather slow to respond and the client wants to put a "timeout" in place so that if it is taking too long to navigate to the destination page, to cancel the browser navigation and show a message.
Is it possible with Javascript to cancel a browser navigation that is already in progress (i.e. the request to the destination site has already been made)? If so, how?

I conducted a simple test, it is possible. I used PHP to conduct the test but this will not be an issue if you use a different language. The bottom line is JavaScript can do it as seen in cancel.php. Please see the sample code:
sleep.php
<?php
sleep(30);
echo 'hello';
?>
cancel.php
<h1>hello?</h2>
<script type="text/javascript">
location.href='sleep.php';
setTimeout(function(){
location.href='#';
alert('it is taking too long to respond, probably the site is down!');
}, 10000);
</script>
After running cancel.php, it will redirect to sleep.php. After 10 seconds of loading time, it will stop loading sleep.php and conclude that the site is down.

You can redirect to somewhere else, while the current DOM is still alive.
I ran this simple test, and it redirects to yahoo.com
$("#btn").click(function() {
document.location.href = "http://www.google.com";
document.location.href = "http://www.yahoo.com";
});​
I havent tested with a timer, but seems like it should work, although I cant be sure 100%.
Please post your findings!

Related

How Facebook and Google handles the back button after logout?

I am working on a php project in codeigniter. When a user logs out, he/she is directed to login page. But when he/she clicks the back button of browser, he/she gets to see the home page just before the log out, which definitely not a good thing.
I have added session check on every page so that when a user reloads any page after logout he/she will be directed to login page.
As far as i think, this happens due to web browser using cache for the back button.So one solution as given in many stack overflow forums and others is to clear the cache, which i too did. But another problem came that the document expires after back button, which is not good from the UX point of view.
Another solution is to add javascript code to restrict the page to itself when pressing back button, which surely works. But since the javascript is client side, this won't work if you disable it from browser.
If you check the Gmail or facebook or any good site ,they handle it really well and no ,it's not by just javascript code , as suggested in this forum How Google deals with the Back Button after logout? ,
So my question is how do they handle it in real?
On home page, you'll need to check if SESSION is active.
When user is logging out, you'll need to destroy SESSION.
For example:
-On Home Page
session_start();
if(!isset($_SESSION['variableName']))
{
header("location:login.php");
}
On logout page:
session_start();
session_destroy();
Hope this helps.
One time I got that problem and finally I got many tiny solutions for that.
Put noscript tag in common header file. I return a text when the JS turn off.
<noscript>Your browser does not support JavaScript!</noscript>
Another Method to check the user logged or not at every intervel
setInterval(function(){
$("#autorefresh").load("checklogin.php?screenName=autorefresh");
}, 5000);
And finally put this back prevent js
history.pushState(null, null, 'loginController.php?time=
$currentDateTime; ?>');
window.addEventListener('popstate', function(event) {
history.pushState(null, null, 'loginController.php?time=<?php echo $currentDateTime; ?>');
});
This is my experience knowledge... Thank You

Run jQuery, reload, rinse and repeat...how?

I have the following code;
<script>
$(document).ready(function() {
$('a[href*="profile"]:contains("PETER PAN")').closest('tr').find('.fightActionInnerInner').click();
});
How would I run this, then refresh the page (say every 2-3 seconds) and rerun the script. I'm using Greasemonkey, if that helps. Thanks.
You can use the setTimeOut function with a window.location reload like this:
$(document).ready(function(){
setTimeout(function(){
window.location.reload();
}, 2000);
});
Here is the fiddle of a working example:
jsFiddle
In JavaScript you can reload the page with window.location.reload(), history.go(0) or even window.location.href=window.location.href
The code in document ready function will automatically run again on page reload.
If you want to delay something, you can do this with setTimeout:
setTimeout(function (){
//do something
}, yourMillisecondsToWaitUntilStart);
For your code it would be:
$(document).ready(function(){
$('a[href*="profile"]:contains("PETER PAN")').closest('tr').find('.fightActionInnerInner').click();
setTimeout(function(){
window.location.reload();
}, msToWait
});
Replace msToWait with the number of milliseconds you want to delay the page reload.
Read about the Meta refresh.
You just place this inside the head tag of your page
<meta http-equiv="refresh" content="3">
However, I suggest you read the whole page, specifically these parts (even if you end up using the javascript way of redirecting which other users have suggested since this text shows some general drawbacks of refreshing every few seconds, no matter what way you do it):
Use of meta refresh is discouraged by the World Wide Web Consortium (W3C), since unexpected refresh can disorient users.
Drawbacks
Meta refresh tags have some drawbacks:
If a page redirects too quickly (less than 2-3 seconds), using the "Back" button on the < next page may cause some browsers to move back to the redirecting page, whereupon the > redirect will occur again. This is bad for usability, as this may cause a reader to be "stuck" on the last website.
A reader may or may not want to be redirected to a different page, which can lead to user dissatisfaction or raise concerns about security.
Alternatives
For refresh
An alternative method is to provide an interaction device, such as a button, to let the user choose when to refresh the content. Another option is using a technique such as Ajax to update (parts of) the Web site without the need for a complete page refresh, but this would also require that the user enable JavaScript in their browser.
If you don't really need a page refresh, I suggest you use setTimeout javascript function, as already mentioned in another answer (except use it to trigger the click, not reload the page) since refreshing the page is a big thing to do for something small (if the click does something small, which I'm guessing it does).

How do you break out of frames without breaking the browser's back button?

A site that links to mine keeps my site in a frame, so I added the following JavaScript to my page:
if (window.top.location != window.location) {
window.top.location = window.location
}
Now if I get to my site via the offending site, my site successfully breaks out of the frame. But the back button breaks! The back button sends the user to the framed version of my site, which immediately breaks out again, returning him to where he was trying to leave! Is there a simple way to fix this?
window.top.location.replace(window.location);
The replace method is specifically for this purpose. It replaces the current item in the history state with the new destination so that the back button won't go through the destination you don't want.
jfriend00's answer is indeed correct. Using the window.location.replace method will work without affecting the back button.
However, I'd just like to note that whenever you want to stop a page from being framed, you should do more than just that! There are a couple methods of preventing a simple script like that from breaking out of the frame, which work in many modern browsers. Perhaps you can disable the page, display a message with a link to the full page, something like that. You could also use the X-Frame-Options response header that tells the browser not to display the page in a frame. If you don't take some of these measures, your site could be clickjacked.
Another solution is to open your site in a new window leaving a friendly message in the iframed site:
if (parent.frames.length)
{ window.open("mySite.htm", "MySite");
location.href= "framedMessage.htm";
}
Where framedMessage.htm contains some friendly/warning message.

Detect when a user leaves a website

I am trying to create my own website access library (for fun) like Google Analytics where I can detect when a user accesses my website, what pages they view etc.
Is there a way to determine when the user leaves a page &/or leaves the website for good?
I have successfully coded (in python) the detecting when the user 1st accesses my site (using a cookie) & how to determine what pages they view. But I don't know how I could detect when they user leaves the website for good?
Is there a way in javascript (maybe I can detect when the page/url is changing?). I know in HTTP there is a referrer header that tells me where the user came from, maybe when the user moves to another website (outside of mine), I can be notified of this (because I will be the referrer in that HTTP request)? Am I correct?
Using jquery you can trigger this:
$(window).bind('beforeunload', function() {
// ajax call perhaps
// triggering a write to db or filesystem...
});
Pure javascript way:
<html>
<head>
<script>
function closeIt()
{
return "Any string value here forces a dialog box to \n" +
"appear before closing the window.";
}
window.onbeforeunload = closeIt;
</script>
</head>
<body>
<a href="http://www.somewhere.com">Click here to navigate to
www.somewhere.com</a>
</body>
</html>
As long the user plays by the rules you expect the onbeforeunload will work. That means, closing a tab, or closing the window, or navigating to another site.
However, you have no way to detect this reliably with javascript, onbeforeunload doens't fire in many cases, such as shutting down the browser (ctrl+q), browser crash, history (back) and opera and some versions of chrome have limited support to onbeforeunload.
If you want to detect it with high precision, you must send Ajax requests periodically that shows the user is "still alive". register those requests in a database or file and analyze it by the time sequence.
So, if you "ping" the database every 20 seconds you can know from pretty simple queries that the browser hasn't "pinged" after a short while, and determine the user is no longer in the site.
You can mark all links on your site as inner or outer links. They must point to your site, but then redirect to location, selected by user. Before redirection you can point that user left away from your site.
But.
I'd better putted on every page on your site a little script which (say every 20-30 sec) make a GET request to specific url on your site. So you can track number of each user requests.
There is an unload event you can handle in JavaScript. For example:
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
Unfortunately, there is no way to tell where the user is actually going when they leave the current page (unlike a referrer, when you enter the page).
One idea is, to set a variable (perhaps in database) in the unload handler (via AJAX call or what not), and then remove it if user enters another page shortly after that. Whichever record is not removed (or deactivated - soft deletes) is your last exit event before the user actually bounced off your web site or closed the browser.
You can bind to the window.beforeunload or window.unload.
Neither of these methods are very reliable though.

javascript window unload event

I am calculating how many users online, but if a person close a window without logging out, he is not online, I need to make that user logout dynamically through javascript or jquery.
when i use body onunload event to check this it works but if i refresh the page it also calls the body unload event.
Here is my code
<script>
function LogmeOut()
{
window.location='logout.php';
}
</script
<body onUnload="LogmeOut();">
.....
.....
</body>
The logout php will signout the current user before closing the window.
Any suggestions?
I don't think there is a reliable way to tell.
Best thing to do is when the user accesses a page, update their activity in the database and set a new expiry (e.g. 15 minutes).
If the user has had no activity when you query, you could perhaps count them as offline.
I like Alex's answer, if you go about tracking your active users through JavaScript, it will definitely have errors due to crashing browsers, "active" but actually inactive users who left their browsers idle etc...
Alex's method avoids all that.
instead of using window.onunload, I would prefer using window.onbeforeunload and then make an ajax call to logout.php like following:
window.onbeforeunload = function(){
// make an ajax call to logout.php
};

Categories