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
};
Related
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).
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!
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.
I would like to create a webpage with browser specific in javascript.
For example:
can I use code like this in my coding part
chrome.tab.onRemoved.addListener() in my webpage.
If it is possible please suggest me.
What exactly are you tring to acheive?
If you want to know when the tab in which your webpage is loaded is closed, then window.onunload should help you.
If you want to know when another webpage is closed, you cannot do this.
UPDATE:
You said that you want to know when the user closes the browser or tab. This is not possible.
But for your purpose (getting feedback), I think all you need is to differentiate whether the user is navigating to a link in your page, or whether the user is typing another URL(or by clicking a favorite).
I think for your requirement, whether the user closes the browser, or whether he types another URL, is the same - the user is navigating away from your site, and at that time you say you want to collect feedback.
This can be done in javascript.
For all the clicks in your page that
might lead to a page refresh
(hyperlinks, buttons,...), set a flag.
In window.onunload, check whether
this flag is set.
- If it is set, then
the user has clicked a link in your
page, do nothing.
- If the flag is not
set then the user is navigating away,
time to collect feedback.
Let me know if this would work.
PS: Note that popups/any distractions during window.unload can be very annoying.
I understand that this probably is the requirements given to you. But if possible, try other mechanisms to collect (voluntary) feedback from the user.
No, you cannot access extension-specific APIs from webpages.
The Navigator object contains all information about the visitor's browser.
https://developer.mozilla.org/en-US/docs/Web/API/Window.navigator
I think this is pretty much the extent of what is possible in terms of interacting with the specific browser. You can't access other tabs (for security reasons) or tell when a tab is closed.
You can use use the onbeforeunload event:
<html>
<head>
<script>
var exit = 1;
function handleClose()
{
if (exit)
{
alert("Closing");
}
}
</script>
</head>
<body onbeforeunload="handleClose()">
Navigate to other page
</body>
</html>
I need a solution for the page refresh and the back button when using AJAX.
I'm using simple javascript for the AJAX implementation.
If anybody could send a code snippet I would be very grateful.
If you're using jQuery, there's the history plugin.
Here's a solution that I've used in some of my pages. Add this to pages that changes are made at.
window.onbeforeunload = function() {
window.name = "reloader";
}
this triggers when you leave those pages. You can also trigger it if there were changes made. So that it won't unnecessarily reload the page that needs reloading.
Then on pages that you want to get reloaded on after a the browser "back" use.
if (window.name == "reloader") {
window.name = "no";
location.reload();
}
this will trigger a reload on the page you need reloading to.
essentially, you need to use & monitor the hash portion of the url...
http://.../path?parms#hashpart
Whan you change the hash, iirc window.location.hash , it won't reload the page, but your ajax can monitor, and respond to it.
The onbeforeunload event can be useful to guard against refreshing but it fires if you navigate away or refresh. If you require that users login to the app you can always show a generic message advising against navigating away and refreshing. If users click your app log out button set a var to disable the warning. Could probably also make a 'Close' button that does the same thing.
Try PathJS it does not require jQuery or any other additional lib.