Detect When Page is Not Visible Using JavaScript

Demonstration

See what happens when you minimise this page or jump to another browser tab.

You’ve been away, haven’t you!

Description

The Page Visibility API is an event driven API that lets you know when the HTML page is visible or in focus on the client side web browser. There are various uses for this such as ensuring you have the complete attention of the user or perhaps initiating an auto-save of any uncommitted data.

The demonstration on this page will log each time the page is made visible or hidden as well as changing the page title to say “Come Back!” and a message “You’ve been away, haven’t you!” that appears then fades out anytime the page comes back in to focus.

Further Uses and Ideas

  • TBC

Limitations

14th November 2019 : Chrome on iOS does not detect a tabbed session being hidden behind another tab. It does detect the Chrome app being minimised or overridden by another app.

How it Works

Please find below a self-contained HTML snippet with inbuilt CSS and JavaScript

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page Visibility API</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var visibilityChange = (function (window) {
var inView = false;
return function (fn) {
	window.onfocus = window.onblur = window.onpageshow = window.onpagehide = function (e) {
		if ({focus:1, pageshow:1}[e.type]) {
			if (inView) return;
			fn("visible");
			inView = true;
		} else if (inView) {
			fn("hidden");
			inView = false;
		}
	};
};
}(this));
visibilityChange(function (state) {
var d = new Date();
var n = d.toLocaleTimeString();
document.getElementById("textoutput").innerHTML= n +': Page is ' + state + '<br />'+ document.getElementById("textoutput").innerHTML;
if (state=="hidden")
{
	$("#message").fadeIn();
	document.title = "Come Back!";
}
if (state=="visible")
{
	$("#message").fadeOut(2000);
	document.title = "Page Visibility API";
}
});
</script>
<style>
#message {
	display: none;
}
</style>
</head>
<body>	
	<h1>Page Visibility API</h1>
	<div id="message"><h2>You’ve been away, haven’t you!</h2></div>
	<div id="textoutput"></div>
</body>
</html>

Relevant Links

Page Visibility API

Version History

Version Date Description
Version 1.0 10/11/2016 Version 1

Comments For This Page

Agreed that Chrome on iOS does not detect a tabbed session being hidden behind another tab. It does detect the Chrome app being minimised or overridden by another app. We will add a Limitations section to record this.
By Daft Logic on 14th November 2019
Not working on iOS Chrome iPhone
By Yaroslav on 14th November 2019
You should try to open a new tab, go to it and return and check out what happens to it next.
By Nobody on 6th February 2019

Add your own comment below and let others know what you think: