We need to track the EFFECTIVE time on site of our users
Most users, when they're done, leave the tab open and move to another tab
Time on site it's extremely inaccurate
Is there a Javascript Event to track the "loss of focus" of the current tab ?
This should work both on tab switch and on browser window losing focus:
function onBlur() {
document.body.className = 'blurred';
};
function onFocus(){
document.body.className = 'focused';
};
if (/*#cc_on!#*/false) { // check for Internet Explorer
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
I would do something with mousemove and scroll and count a visitor as active as long as either of those trigger within some interval. That will also cover them leaving the browser open and leaving the computer.
Which tab you are talking about? Is it your Nav/menu tab or Browser tab. I feel, you mean browser tab!
I think it is not possible accurately. But what if you track few events like mousemove, focus etc and then fire an event that same some data (counter) on server. When user is on your page then he will do something something like move mouse, click somewhere etc. So difference in first page load and last event can tell the usage stat.
Though question was asked long ago, it might still be found by someone. In this case, use Page Visibility API:
https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
document.visibilityState - to get a current tab state.
document.onvisibilitychange - to add a callback for state change.
<script>
document.onvisibilitychange = () => {
if (document.visibilityState === "hidden") {
console.log("tab inactive");
}
if (document.visibilityState === "visible") {
console.log("tab active");
}
};
</script>
Related
Hi i have notification div(divNotify) with some information and a timer in masterpage
Protected Sub Timer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
Me.GetNotification_Stats()
ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "Alert", "Show_NotifyDiv();", True)
Catch ex As Exception
Me.lblError.Visible = True
Me.lblError.InnerText = ex.Message
End Try
End Sub
divNotify will display in some interval of time.
here i need when the user will minimize the browser he will be notified by blinking browser and change color of browser
but first of all how do i know if the browser is minimized or not in javasript
here i am using jquery for show div tag
function Show_NotifyDiv() {
$("#div_NotificationOuter").show(1000);
$("#div_NotificationOuter").animate({ bottom: '+=30px' }, 4000);
}
Its impossible to find out whether the page is minimized via JavaScript, but you can use Visibility API to determine, whether the page is visible to user or not.
Currently available in Chrome, Mozilla and IE10.
https://developer.mozilla.org/en/DOM/Using_the_Page_Visibility_API
http://code.google.com/chrome/whitepapers/pagevisibility.html
http://www.nczonline.net/blog/2011/08/09/introduction-to-the-page-visibility-api/
The Page Visibility API provides events you can watch for to know when a document becomes visible or hidden, as well as features to look at the current visibility state of the page.
Notes: The Page Visibility API is especially useful for saving
resources and improving performance by letting a page avoid performing
unnecessary tasks when the document isn't visible.
When the user minimizes the window or switches to another tab, the API sends a visibilitychange event to let listeners know the state of the page has changed. You can detect the event and perform some actions or behave differently. For example, if your web app is playing a video, it can pause the video when the user puts the tab into the background, and resume playback when the user returns to the tab. The user doesn't lose their place in the video, the video's soundtrack doesn't interfere with audio in the new foreground tab, and the user doesn't miss any of the video in the meantime.
Use cases
Let's consider a few use cases for the Page Visibility API.
A site has an image carousel that shouldn't advance to the next slide unless the user is viewing the page
An application showing a dashboard of information doesn't want to poll the server for updates when the page isn't visible
A page wants to detect when it is being prerendered so it can keep accurate count of page views
A site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off)
Developers have historically used imperfect proxies to detect this. For example, watching for blur and focus events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user. The Page Visibility API addresses this.
Example
View live example (video with sound).
The example, which pauses the video when you switch to another tab and plays again when you return to its tab, was created with the following code:
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
var videoElement = document.getElementById("videoElement");
// If the page is hidden, pause the video;
// if the page is shown, play the video
function handleVisibilityChange() {
if (document[hidden]) {
videoElement.pause();
} else {
videoElement.play();
}
}
// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" || hidden === undefined) {
console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
// Handle page visibility change
document.addEventListener(visibilityChange, handleVisibilityChange, false);
// When the video pauses, set the title.
// This shows the paused
videoElement.addEventListener("pause", function(){
document.title = 'Paused';
}, false);
// When the video plays, set the title.
videoElement.addEventListener("play", function(){
document.title = 'Playing';
}, false);
}
Source: MDN: Page Visibility API
Additionally to c69's Answer, I would propose the library isVisible.
It has utility functions to access the W3C Page visibility API and you do not have to worry about cross browser support (unifies moz- or webkit-prefixed functions)
maybe check the size of the window? i'm just guessing.
We will be patient, but visibilityState is coming:
W3C defines the visibility state
I am using onbeforeunload function. I want to alert different message when any one click on browser back button , browser refresh button ,browser tab close button and browser close button .So how can i track all the events inside onbeforeUnload functions .
My code structure is like that
<body onbeforeunload="return closePage();">
<script type="text/javascript">
function closePage() {
if(back button click){
alert("back button");
} else if(refresh button click || f5){
alert("refresh button click");
} else if(browser tab close){
alert("tab close");
} else {
alert("browser closed");
}
}
</script>
Any idea to fix this? Thanks a lot.
To the best of my knowledge, what you want is not possible. For security reasons most browsers won't allow these kinds of things.
You can, however, catch a few things. Like keydown on the f5 key. That way you can do some stuff there before the "onbeforeunload" function runs if you like.
But you can't bind an event on the "back" button for instance. Or "ctrl+r".
So I'm afraid you'll have to reconsider your options, and go with some other solution.
you can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
/* Do you small action code here */
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload
Thankyou so much for reply.But i have found some code
if(window.event){
if (window.event.clientX < 40 && window.event.clientY < 0)
{
alert("Backbutton is clicked");
}
else
{
return exitPage();
}
}
else{
if(event.currentTarget.performance.navigation.type == 2)
{
alert("Back button click in mozilla");
}
if(event.currentTarget.performance.navigation.type == 1)
{
return exitPage();
}
}
Using this code i can track the back button event but it only working in IE
I want my javascript to be trigged when:
The current IE tab is switched out when multiple IE tabs are open.
When the current IE tab is closed.
I don't want my JS code be trigged by the in-page pops up dialogs.
When the whole IE window closed.
The lose focus event may not work for me because there are pop up diaglogs in my page, so when it pops out, the IE tab will lose focus, but since the tab is not switched or closed, I don't want my javascript to be trigged here.
Is there any solution? I am wondering if there's something like entering tab / leaving tab, or tab-switching events?
Some interesting links, but not resolve my question.
Is there a way to detect if a browser window is not currently active?
Hook into tab changed event of browser
if you use 'jQuery', you can easily do it .
$(window).blur(function(){
// your code
});
$(window).focus(function(){
// your code
});
here is the link which provides one more method to do it.
you may be interested in
(function(){
function doOnFocus(){ console.log("focus"); }
function doOnBlur(){ console.log("blur"); }
function doOnLeave(){ console.log("leave"); }
if('onfocusout' in document){
document.onfocusout = doOnBlur;
document.onfocusin = doOnFocus;
}else{
window.onblur = doOnBlur;
window.onfocus = doOnFocus;
}
window.onbeforeunload = doOnLeave;
})();
In javascript there is an event on window close it is not IE specific but is mostly used to call an alert before the user leaves the page. It's one of my pet peeves and is very annoying but may be what you are looking for.
window.onbeforeunload = yourfunctionthatexecutes;
My extension opens up a series of additional windows. I want those windows to close when the user closes the main Firefox window. I know you can detect when a tab closes (and perhaps I should just look for the "final" tab close?) but I want to know when "all tabs" have been closed.
In short, how can I detect when the main Firefox window is closed from an extension?
You can listen the unload event.
If you script run on all type of windows, then check the url whether a browser window.
window.addEventListener('unload', function(event) {
if (event.target.location.href !== 'chrome://browser/content/browser.xul') {
return;
}
// do you stuff...
}, false);
I found one solution, although it doesn't actually listen for a particular event. Instead, we setup an interval to check if the tab container is still available.
setInterval(function() {
if (typeof gBrowser.mTabContainer === 'undefined') {
// Rest of your code...
}
}, 500);
If there's a cleaner way of doing this, I'd be more than happy to see it.
Got an issue with safari loading old youtube videos when back button is clicked. I have tried adding onunload="" (mentioned here Preventing cache on back-button in Safari 5) to the body tag but it doesn't work in this case.
Is there any way to prevent safari loading from cache on a certain page?
Your problem is caused by back-forward cache. It is supposed to save complete state of page when user navigates away. When user navigates back with back button page can be loaded from cache very quickly. This is different from normal cache which only caches HTML code.
When page is loaded for bfcache onload event wont be triggered. Instead 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 it is set to true.
Kludgish solution is to force a reload when page is loaded from bfcache.
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
If you are using jQuery then do:
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload()
}
});
All of those answer are a bit of the hack. In modern browsers (safari) only on onpageshow solution work,
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
but on slow devices sometimes you will see for a split second previous cached view before it will be reloaded. Proper way to deal with this problem is to set properly Cache-Control on the server response to one bellow
'Cache-Control', 'no-cache, max-age=0, must-revalidate, no-store'
Yes the Safari browser does not handle back/foreward button cache the same like Firefox and Chrome does. Specially iframes like vimeo or youtube videos are cached hardly although there is a new iframe.src.
I found three ways to handle this. Choose the best for your case.
Solutions tested on Firefox 53 and Safari 10.1
1. Detect if user is using the back/foreward button, then reload whole page or reload only the cached iframes by replacing the src
if (!!window.performance && window.performance.navigation.type === 2) {
// value 2 means "The page was accessed by navigating into the history"
console.log('Reloading');
//window.location.reload(); // reload whole page
$('iframe').attr('src', function (i, val) { return val; }); // reload only iframes
}
2. reload whole page if page is cached
window.onpageshow = function (event) {
if (event.persisted) {
window.location.reload();
}
};
3. remove the page from history so users can't visit the page again by back/forward buttons
$(function () {
//replace() does not keep the originating page in the session history,
document.location.replace("/Exercises#nocache"); // clear the last entry in the history and redirect to new url
});
You can use an anchor, and watch the value of the document's location href;
Start off with http://acme.co/, append something to the location, like '#b';
So, now your URL is http://acme.co/#b, when a person hits the back button, it goes back to http://acme.co, and the interval check function sees the lack of the hash tag we set, clears the interval, and loads the referring URL with a time-stamp appended to it.
There are some side-effects, but I'll leave you to figure those out ;)
<script>
document.location.hash = "#b";
var referrer = document.referrer;
// setup an interval to watch for the removal of the hash tag
var hashcheck = setInterval(function(){
if(document.location.hash!="#b") {
// clear the interval
clearInterval(hashCheck);
var ticks = new Date().getTime();
// load the referring page with a timestamp at the end to avoid caching
document.location.href.replace(referrer+'?'+ticks);
}
},100);
</script>
This is untested but it should work with minimal tweaking.
The behavior is related to Safari's Back/Forward cache. You can learn about it on the relevant Apple documentation: http://web.archive.org/web/20070612072521/http://developer.apple.com/internet/safari/faq.html#anchor5
Apple's own fix suggestion is to add an empty iframe on your page:
<iframe style="height:0px;width:0px;visibility:hidden" src="about:blank">
this frame prevents back forward cache
</iframe>
(The previous accepted answer seems valid too, just wanted to chip in documentation and another potential fix)
I had the same issue with using 3 different anchor links to the next page. When coming back from the next page and choosing a different anchor the link did not change.
so I had
House 1
View House 2
View House 3
Changed to
House 1
View House 2
View House 3
Also used for safety:
// Javascript
window.onpageshow = function(event) {
if (event.persisted) {
window.location.reload()
}
};
// JQuery
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload()
}
});
None of the solutions found online to unload, reload and reload(true) singularily didn't work. Hope this helps someone with the same situation.
First of all insert field in your code:
<input id="reloadValue" type="hidden" name="reloadValue" value="" />
then run jQuery:
jQuery(document).ready(function()
{
var d = new Date();
d = d.getTime();
if (jQuery('#reloadValue').val().length == 0)
{
jQuery('#reloadValue').val(d);
jQuery('body').show();
}
else
{
jQuery('#reloadValue').val('');
location.reload();
}
});
There are many ways to disable the bfcache. The easiest one is to set an 'unload' handler. I think it was a huge mistake to make 'unload' and 'beforeunload' handlers disable the bfcache, but that's what they did (if you want to have one of those handlers and still make the bfcache work, you can remove the beforeunload handler inside the beforeunload handler).
window.addEventListener('unload', function() {})
Read more here:
https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Releases/1.5/Using_Firefox_1.5_caching