Change favicon, using Visibility API - javascript

I have seen some websites (discord. hotjar), using the Visibility API to show a bullet when the tab is inactive, and hide it when its active again,
How we can do that?

For this, you need to create two different favicons for each mode and toggle between them using the Visibility API. Something like this:
// Set the name of the hidden property and the change event for visibility
let hidden;
let 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 link = document.querySelector("link[rel~='icon']");
if (!link) {
link = document.createElement('link');
link.rel = 'icon';
document.getElementsByTagName('head')[0].appendChild(link);
}
function handleVisibilityChange() {
if (document[hidden]) {
link.href = 'https://www.linkpicture.com/q/favicon2.ico';
} else {
link.href = 'https://www.linkpicture.com/q/favicon1_1.ico';
}
}
// 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);
}
Preview:

Related

How can I use the full screen with trigger script?

It's not working fullscreen when triggering a click. It opens the new page when I clicked the Icon or image. The new page shows fullscreen without any click, but it's not changed the full screen.
<button id="test" onclick="launchFullscreen(document.documentElement);">Click Me</button>
var ele = document.getElementById('test');
ele.click();
function launchFullscreen(element) {
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
}
}
In newer versions of browsers, you can use this script.
Here's how to do it:
function requestFullScreen(element) {
// Supports most browsers and their versions.
var requestMethod = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || element.msRequestFullScreen;
if (requestMethod) { // Native full screen.
requestMethod.call(element);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
} }
HTML Button:
<button onclick="requestFullScreen(document.body)">Go Fullscreen</button>
The user obviously needs to accept the fullscreen request first, and there is not possible to trigger this automatically on pageload, it needs to be triggered by a user (eg. a button)

How to detect Android Chrome sleep event?

Do you guys have any idea how to detect mobile Chrome sleep event? I tried with:
window.onblur = fnPause;
document.onfocusout = fnPause;
document.body.onfocusout = fnPause;
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.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
if (typeof document.addEventListener === "undefined" ||
typeof document[hidden] === "undefined") {
// doesn't support event listeners :(
} else {
// Handle page visibility change
document.addEventListener(visibilityChange, function() {if (document[hidden]) {fnPause();} else {fnResume();}}, false);
}
Still fnPause() is never called when I leave the html5 game open and phone goes sleep mode and locks.
This question is not a duplicate of - Is it possible, in JavaScript, to detect when the screen is turned off in the Android & iOS browsers . Two of the solutions I tried above (blur and pagevisibility) without success and the third - using timers - only detects resume event and not sleep.

Detect when browser tab/window is active [duplicate]

This question already has answers here:
How to tell if browser/tab is active [duplicate]
(6 answers)
Closed 8 years ago.
Is It possible to detect when browser window Is active/inactive
I did try:
$(window).on('focus', function(){
console.log(1);
});
$(window).on('blur', function(){
console.log(2);
});
But it seems that it's working only when user will click the window.
but showing 2 when user will click eg. browser address bar.
What I want to achieve is to detect when current tab is active one.
How to improve this code?
Active means when the tab is visible. But if you want to tell if the user's mouse is directly on the page, you could use this:
<html onmouseenter="document.getElementById('h1').innerHTML = 'active'"onmouseleave="document.getElementById('h1').innerHTML = 'not active'">
<body style="width:100%;height:100px">
<h1 id="h1">not active</h1>
</body>
</html>
With the simple code above you can tell if the users mouse is on the page or not
EDIT: using the page visibility API:
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
}
else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
}
else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
}
else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
function handleVisibilityChange() {
if (document[hidden]) {
//Not visible, Do whatever
}
else {
//Visible
}
}
if (typeof document.addEventListener === "undefined" ||
typeof document[hidden] === "undefined") {
alert("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
}
else {
document.addEventListener(visibilityChange, handleVisibilityChange, false);

Detect if browser tab is active or user has switched away

How can I detect if a user is switching to another browser tab?
Currently, I have this:
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
$('.message').html('<div class="alert alert-error">Oops. You navigated away from the ads <a id="start" class="butt green">Resume</a></div>');
var myDiv = $("#bar");
myDiv.clearQueue();
myDiv.stop();
clearInterval($timer);
$timer = null;
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
});
But that only works when the user is minimizing the active window.
Now we can use the visibility API.
To deal with the different browser-specific syntaxes, I made this small code :
var vis = (function(){
var stateKey, eventKey, keys = {
hidden: "visibilitychange",
webkitHidden: "webkitvisibilitychange",
mozHidden: "mozvisibilitychange",
msHidden: "msvisibilitychange"
};
for (stateKey in keys) {
if (stateKey in document) {
eventKey = keys[stateKey];
break;
}
}
return function(c) {
if (c) document.addEventListener(eventKey, c);
return !document[stateKey];
}
})();
Usage :
var visible = vis(); // gives current state
vis(aFunction); // registers a handler for visibility changes
Example :
vis(function(){
document.title = vis() ? 'Visible' : 'Not visible';
});
Demonstration page
These 3 lines of code worked for me
document.addEventListener("visibilitychange", function() {
document.title = document.hidden ? "I'm away" : "I'm here";
});
reference link: document.hidden
demo: https://iamsahilralkar.github.io/document-hidden-demo/
CASE 1
Just add this EventListener in your constructor.
document.addEventListener("visibilitychange", function() {
if (document.hidden) {
//do whatever you want
console.log("Hidden");
}
else {
//do whatever you want
console.log("SHOWN");
}
});
CASE 2
See here If you change tab $(window).blur(function () function will call and If you again come to this tab $(window).focus(function () function will call.
Add this code in your constructor
$(window).focus(function () {
//do something
console.log("You are in this tab");
});
$(window).blur(function () {
//do something
console.log("You left this tab");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Click here and click outside of this..</p>
If you want to detect whether the tab is visible to the user, use document.visibilityState to perform the check (a read-only property). Although document.hidden works too, as others have written, then W3C considers it 'historical' and recommends using the former approach.
If you only want to know whether the tab is active, use document.hasFocus() to perform the check. In this case, the tab could still otherwise be visible, but not active (e.g. two parallel view browser windows, where only one is active, both visible).
If you want capture the change to the state of visibility (and naturally also the active state in this case), then listen to the visibilitychange event from the Page Visibility API.
Example using all three
// Capture change to visibility
document.addEventListener("visibilitychange", function() {
// Check if tab content is visible
if (document.visibilityState) {
console.log("Tab is visible!")
}
// Check if tab is active
if (document.hasFocus()) {
console.log("Tab is active!");
}
});
Handling browser compatibilities
You can set up the following checks to cover incompatible browsers.
Note: Does not include hasFocus() as it's compatible all the way to IE6.
var visibilityState, visibilityChange;
if (typeof document.visibilityState !== "undefined") {
visibilityState = "visibilityState";
visibilityChange = "visibilitychange";
}
else if (typeof document.mozVisibilityState !== "undefined") {
visibilityState = "mozVisibilityState";
visibilityChange = "mozvisibilitychange";
}
else if (typeof document.msVisibilityState !== "undefined") {
visibilityState = "msVisibilityState";
visibilityChange = "msvisibilitychange";
}
else if (typeof document.webkitVisibilityState !== "undefined") {
visibilityState = "webkitVisibilityState";
visibilityChange = "webkitvisibilitychange";
}
if (visibilityChange != null && visibilityState != null) {
document.addEventListener(visibilityChange, function() {
if (document[visibilityState]) {
console.log("Tab is visible!")
}
}, false);
}
Quick MDN references
visibilityState
hasFocus()
visibilitychange
This is an ES6 multi-browser-solution which I use to determine the tab visibility. I took inspiration from Deny's solution and tailored it to my needs.
const vis = (c) => {
let self = this
const browserProps = {
hidden: "visibilitychange",
msHidden: "msvisibilitychange",
webkitHidden: "webkitvisibilitychange",
mozHidden: "mozvisibilitychange",
}
for (item in browserProps) {
if (item in document) {
eventKey = browserProps[item]
break
}
}
if (c) {
if (!self._init && !(typeof document.addEventListener === "undefined")) {
document.addEventListener(eventKey, c)
self._init = true
c()
}
}
return !document[item]
}
vis(() => {
let tabVisibility = vis() ? 'Visible' : 'Not visible';
console.log(tabVisibility)
})

check if tab open as active

I need determine, if current page is active.
I know i can find if tab get/lost focus with this answer:
https://stackoverflow.com/a/1760268/449553
It is ok, if tab state change, BUT i need to get initial value.
There is a few ways to open page:
going by link in this active tab
open in new tab
open in new background tab
I understand, that page need some time to load. So I need to get this value after DOM loaded.
Is there any way to find this value?
Try pagevisibility:
var visibilityChange,hidden, state;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
state = "visibilityState";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
state = "mozVisibilityState";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
state = "msVisibilityState";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
state = "webkitVisibilityState";
}
document.addEventListener(visibilityChange, function() {
document.title = document[state];
}, false);
document.title = document[state];
if(document[state]==="hidden"){
//hidden
}else{
//show
}
See the compatibility

Categories