Reputation: 2536
Hi i would like to display a simple alert using JavaScript whenever user is viewing mypage (i.e. after switching tabs, or changing windows; between application).
So for example a user has 3 tabs namely google.com, stackoverflow.com and mysite.com. When ever a user switching from google.com to mysite.com i would like to have a simple alert.
Which basically the opposite of onUnload.
I tried using
onLoad, but this does not work as i intended to be.
Does anyone know how to do this?
Cheers,
Upvotes: 1
Views: 949
Reputation: 15571
I simply added onfocus handler to the body and its working great.
<body onfocus="javascript: alert('Hi');">
Upvotes: 0
Reputation: 9151
You just add this to the script:
window.onfocus = function () { alert('stuff'); };
You should mostdefinitly NOT do that. It will block the user from doing ANYTHING as the alert will blur the page and result in your page being blocked completely. Even if you prevent that from happening, an alert is blocking and highly annoying in any case.
Upvotes: 0
Reputation: 171
You can use the page visibility API for this. Check out this excellent jsfiddle:http://jsfiddle.net/0GiS0/cAG5N/
You need some boilerplate from the fiddle to make it work across different browsers, but this is the core of it:
function handleVisibilityChange() {
if (!document.hidden) {
alert('the dialog');
}
}
document.addEventListener("visibilitychange", handleVisibilityChange, false);
Upvotes: 1