Detect if WhatsApp is installed - javascript

Using Android or a desktop browser, please visit this WhatsApp test page and click the Send button. If WhatsApp is not installed it will show you a message.
How does the code detection on that page work? I tried the following but nothing happens.
try {
location.href = 'whatsapp://send/?phone=62812345678&text=test';
} catch (e) {
console.log(e);
}

Looking at the page, it appears that at least on Chrome, they programmatically open an iframe with the src of whatsapp://send/?phone=<number>&text=test. They then start a 1000ms timeout after which the "Looks like you don't have WhatsApp installed!" text is shown. This timeout is cancelled by an blur event handler, meaning that their check is based on your device opening WhatsApp when that URL is loaded, which blurs the window.
The function which triggers after the timeout also seems to check if the timeout took longer than 1250ms. I suspect that this handles the case where your phone's browser stops executing JS timers when it changes apps.
On IE, they use window.navigator.msLaunchUri, which accepts a noHandlerCallback.
See for yourself by opening your browser's devtools and searching for WhatsAppApiOpenUrl. On Chrome, the Search can be found from the devtools' menu:
Here's some example code.
const detectWhatsapp = (phone, text) => {
const uri = `whatsapp://send/?phone=${encodeURIComponent(
phone
)}&text=${encodeURIComponent(text)}`;
const onIE = () => {
return new Promise((resolve) => {
window.navigator.msLaunchUri(
uri,
() => resolve(true),
() => resolve(false)
);
});
};
const notOnIE = () => {
return new Promise((resolve) => {
const a =
document.getElementById("wapp-launcher") || document.createElement("a");
a.id = "wapp-launcher";
a.href = uri;
a.style.display = "none";
document.body.appendChild(a);
const start = Date.now();
const timeoutToken = setTimeout(() => {
if (Date.now() - start > 1250) {
resolve(true);
} else {
resolve(false);
}
}, 1000);
const handleBlur = () => {
clearTimeout(timeoutToken);
resolve(true);
};
window.addEventListener("blur", handleBlur);
a.click();
});
};
return window.navigator.msLaunchUri ? onIE() : notOnIE();
};
Please note that it adds an event listener each time it's called. If you're rolling this out into production, please use window.removeEventListener to remove handleBlur after the promise resolves. It also appends a DOM node into the body, if that matters to you.
Usage example:
detectWhatsapp('<your number here>', 'test').then(hasWhatsapp =>
alert(
'You ' +
(hasWhatsapp ? 'have WhatsApp' : "don't have WhatsApp")
)
)

Here my testing on Android:
Built-in Browser (Webview) and Firefox if WA installed You can use iframe to auto open WhatsApp
Chrome and Opera Need user click action
but luckily I only need this simple code to detect if whatsapp installed
document.querySelector('#openWA').addEventListener('click', function() {
var f = Date.now(),
j = setTimeout(function() {
if (Date.now() - f > 1250)
return;
alert('WA not installed')
}, 1e3);
})
<a href="whatsapp://send/?phone=62812345678&text=test" id="openWA">Send to WhatsApp</button>
<!-- Auto open on WebView and Firefox -->
<iframe id="launcher" src="whatsapp://send/?phone=62812345678&text=test" style="display: none;"></iframe>

If you have jquery, bassed on the code above if whats app does not open open a new page using whatsapp web instead of iframe launcher:
$('a[href^="whatsapp://send?"]').click(function() {
var button = this,
f = Date.now(),
j = setTimeout(function() {
if (Date.now() - f > 1025){
return;
}else{
var newLink = button.getAttribute('href').replace("whatsapp://send?", "https://web.whatsapp.com/send?");
button.setAttribute('href', newLink);
button.setAttribute('target', "_blank");
$(button).closest('div').append('<a class="hide new" href="' + newLink + '" target="_blank" ></a>');
$(button).closest('div').find('a.new')[0].click();
}
}, 1e3);
})

Related

Reduce the impact of third-party code (zendesk)

<script
id="ze-snippet"
src="https://static.zdassets.com/ekr/snippet.js?key=some_zendesk_key"
/>
I'm trying to optimize my web site performance. I've faced a big impact of third-party code to my performance, I think all my bundle has a lower size than zendesk code. How can I load it without impacting on the main thread? Should I use the async or defer tags? Or which approach is better for this case?
This seems to be an issue that tortures so many people without a clear solution.
What I managed to do it to reduce the block time by adding this configuration.
window.zESettings = {
webWidget: {
chat: {
connectOnPageLoad: false
}
}
};
ref https://developer.zendesk.com/embeddables/docs/widget/settings#connectonpageload
ps
I did a performance test to my zendesk helpdesk "domain.zendesk.com" and the results there were even worse
I came across this issue recently and made this hack using a function for loading the zendesk script only when you reached certain point of the doc. I know is kind of dirty but it works:
<script defer type="text/javascript">
(function($, win) {
$.fn.inViewport = function(cb) {
return this.each(function(i,el){
function visPx(){
var H = $(this).height(),
r = el.getBoundingClientRect(), t=r.top, b=r.bottom;
return cb.call(el, Math.max(0, t>0? H-t : (b<H?b:H)));
} visPx();
$(win).on("resize scroll", visPx);
});
};
}(jQuery, window));
$('#trigger_div').inViewport(function(px){
if(px) {
//zopim code
}
});
Starting from this article https://www.newmediacampaigns.com/blog/maintaining-great-site-performanc-using-zendesk-web-widget I have implemented a solution that significantly reduces the load time by at least 3 seconds (in Google Lighthouse).
I have created a fake button in the HTML that will load the Zendesk script and open the widget when clicked. It will also load a localStorage item that will prevent this from happening on subsequent page loads.
⚠️ Warning:
The code relies heavily on how the widget is currently implemented (for example it expects a #launcher and a #webWidget element to appear on the page), so it can break as soon as the original code changes, but at least we will have an improvement in the loading times until they fix it.
Here is the most important part of the code:
HTML Button
<button class="zendesk-button">
<span class="left-icon">
<!-- here you insert the icon -->
</span>
<span class="text">Chat</span>
</button>
JavaScript code
// select the button
const zendeskButton = document.querySelector('.zendesk-button');
// add the script to the page
const loadZendeskScript = () => {
const zenDeskScript = document.createElement("script");
zenDeskScript.id = "ze-snippet";
zenDeskScript.src = "https://static.zdassets.com/ekr/snippet.js?key=HERE_YOU_INSERT_YOUR_KEY";
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] || document.getElementsByTagName('script')[0].parentNode).insertBefore(zenDeskScript, null);
};
// a poller that waits for a condition and executes a callback
const poller = (comparison, callback, timerStep = 250, maxTime = 5000) => {
// why setTimeout instead of setInterval
// https://stackoverflow.com/questions/8682622/using-setinterval-to-do-simplistic-continuous-polling
let currTime = 0;
const checkCondition = () => {
// `comparison` is a function so the condition is always up-to-date
if (comparison() === true) {
callback();
} else if (currTime <= maxTime) {
currTime += timerStep;
setTimeout(checkCondition, timerStep);
}
};
checkCondition(); // calling the function
};
// load the script and execute a callback if provided
const loadZendeskChat = callback => {
loadZendeskScript();
if (callback) {
callback();
}
};
// this function opens the chat
const openZendeskChat = () => {
poller(
() => {
// check that zendesk-related functions are available
return typeof zE !== 'undefined';
},
() => {
// open the widget
zE('webWidget', 'open');
poller(
() => {
// check that the elements exist and that the opacity is already set to "1"
const launcher = document.querySelector('#launcher');
const webWidget = document.querySelector('#webWidget');
return launcher !== null && webWidget !== null && webWidget.style.opacity === '1';
},
() => {
// hide the fake button
zendeskButton.style.opacity = '0';
// save in localStorage
localStorage.setItem('zd_hasOpened', 'true');
}
);
}
);
};
// zendesk management
if (localStorage.getItem('zd_hasOpened')) {
// load the zendesk widget if we find that it was opened
loadZendeskChat();
} else {
// show the fake button if it's the first time it shows
zendeskButton.style.opacity = '1';
}
// This will run when the .zendesk-button element is clicked
zendeskButton.addEventListener('click', () => {
// add a 'Loading' text to the button, as the widget will take some time to load (between 1 and 2 seconds on my laptop)
zendeskButton.querySelector('.text').innerHTML = 'Loading';
// load the zendesk widget
// open the widget and hide the fake button
loadZendeskChat(openZendeskChat);
});
Regarding styles, I have pretty much copied the style in the original widget, converting ems to pixels, but one part I'd like to highlight is the focus style, because in my opinion it helps telling the user that something is happening.
.zendesk-button:focus {
outline: none;
box-shadow: inset 0 0 0 0.21429rem rgb(255 255 255 / 40%) !important;
}

If Deeplink url not work send user to download page

I need to implement a javascript where I can detect if my deep link is worked or not, If it works then it should remain same but if it does not work then it must start download file.
For that, i use timeout function to do it. Here is sample code I used.
setTimeout(function () { window.location = "https://itunes.apple.com/appdir"; }, 25);
window.location = "appname://";
But this code works fine on android and ios but it is creating problem while it comes to the desktop browser. In desktop browser after Deeplink works properly, timeout function do not stops and it redirects to download page.
so finally I want some event which can detect if my Deeplink is worked or not so I can set cleartimeout function to prevent redirecting to downloading URL
I have been facing similar problem, and finally I have found a nice botched job to make it work:
var timer = null;
function setListener() {
window.document.addEventListener("visibilitychange", function(e) {
window.clearTimeout(timer);
timer = null;
window.open('','_self').close();
});
}
function redirectAndroid() {
setTimeout(function () { window.location = "https://itunes.apple.com/appdir"; }, 25);
window.location = "appname://";
}
function redirecIOS() {
setListener();
var beforeApp = new Date().valueOf();
window.location.href = "appname://";
var afterApp = new Date().valueOf();
if (afterApp - beforeApp < 100) {
setTimeout(function() {
"https://itunes.apple.com/appdir";
}, 25);
} else {
if (timer === null) {
timer = setTimeout(function() {
"https://itunes.apple.com/appdir";
}, 200);
}
}
This way, after redirecting to application, if it opens it triggers the event "visibilitychange" before the timeout function, and you clear the timeout avoiding it to redirect to web, and close the browser (if you want). If application is not installed, timeAfterApp - timeBeforeApp is not < 100 so there you set the timeout.
For desktop browser, consider using window blur listener and act accordingly
Blur listener will tell you if user left the tab or browser
window.onblur=()=>{//deeplink check (maybe unsuccessfull?)
window.onfocus=()=>{//deeplink unsucesfull};
}
I would try with a timestamp expression in the timeout.
Something like this (play around with the thresholds as needed):
var clickedTm = +new date;
setTimeout(function () {
if (+new date - clickedTm < 600) {
window.location = "https://itunes.apple.com/appdir";
}
}, 500);
window.location = "appname://";

Make a link from Electron open in browser

Is there any (simple/built-in way) to open a new browser (I mean default OS browser) window for a link from Electron instead of visiting that link inside your Electron app ?
You can simply use :
require("shell").openExternal("http://www.google.com")
EDIT: #Arjun Kava's answer is much better these days.
This answer is quite old and assumes you have jQuery.
const shell = require('electron').shell;
// assuming $ is jQuery
$(document).on('click', 'a[href^="http"]', function(event) {
event.preventDefault();
shell.openExternal(this.href);
});
mainWindow.webContents.on('new-window', function(e, url) {
e.preventDefault();
require('electron').shell.openExternal(url);
});
Requires that you use target="_blank" on your anchor tags.
My code snippet clue accordingly to the depreciations in Electron version ^12.0.0
const win = new BrowserWindow();
win.webContents.setWindowOpenHandler(({ url }) => {
// config.fileProtocol is my custom file protocol
if (url.startsWith(config.fileProtocol)) {
return { action: 'allow' };
}
// open url in a browser and prevent default
shell.openExternal(url);
return { action: 'deny' };
});
To make all Electron links to open externally in the default OS browser you will have to add an onclick property to them and change the href property so it doesn't load anything in the Electron app.
You could use something like this:
aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
aTags[i].href = "#";
}
But make sure the entire document has loaded before doing this otherwise it is not going to work.
A more robust implementation would look like this:
if (document.readyState != "complete") {
document.addEventListener('DOMContentLoaded', function() {
prepareTags()
}, false);
} else {
prepareTags();
}
function prepareTags(){
aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
aTags[i].href = "#";
}
return false;
}
Remember that if you load external files you will have to make them go through this process as well after they are fully loaded.
Some handy solutions can be found in this gist.
By listening on the body, the following solutions will work on <a> tags that may not yet exist when the JavaScript runs, but only appear in the DOM at a later time.
This one by luizcarraro requires jQuery:
$('body').on('click', 'a', (event) => {
event.preventDefault();
require("electron").shell.openExternal(event.target.href);
});
You can change the selector to target only certain links, e.g. '#messages-view a' or 'a.open-external'.
Here is an alternative without any library (derived from zrbecker's):
document.body.addEventListener('click', event => {
if (event.target.tagName.toLowerCase() === 'a') {
event.preventDefault();
require("electron").shell.openExternal(event.target.href);
}
});
Consult the gist for more examples.
I use this method with Electron v.13.
We intercept the user's navigation (window.location) and open the URL in the default browser.
See the doc : https://www.electronjs.org/docs/latest/api/web-contents#event-will-navigate
const { shell } = require('electron');
window.webContents.on('will-navigate', function (e, url) {
e.preventDefault();
shell.openExternal(url);
});
On tsx syntax (Electron):
import { shell } from "electron";
shell.openExternal("http://www.google.com")
In the view component use simple a link:
<a href="https://google.com" target="_blank" rel="noreferrer">
<button type="button">
button title
</button>
</a>
And in file public/electron.js add default behavior for all a link navigations:
function createWindow() {
...
// Open urls in the user's browser
win.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: "deny" };
});
}
To open an external link in an Electron's Project you will need the module Shell (https://www.electronjs.org/docs/api/shell#shell) and the method openExternal.
But if you are looking for an abstract way to implement that logic is by creating a handler for a custom target to your target attribute.
const {shell} = require('electron');
if (document.readyState != "complete") {
document.addEventListener('DOMContentLoaded', function() {
init()
}, false);
} else {
init();
}
function init(){
handleExternalLinks();
//other inits
}
function handleExternalLinks(){
let links = document.getElementsByTagName('a')
let a,i = 0;
while (links[i]){
a = links[i]
//If <a target="_external">, so open using shell.
if(a.getAttribute('target') == '_external'){
a.addEventListener('click',(ev => {
ev.preventDefault();
let url = a.href;
shell.openExternal(url);
a.setAttribute('href', '#');
return false;
}))
}
console.log(a,a.getAttribute('external'))
i++;
}
}
To run an Electron project in your actual browser (Chrome, Mozilla, etc), add this to your script are external script:
aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
aTags[i].href = "#";
}

Possible to detect if a user has multiple tabs of your site open?

I'm just thinking about the whole site registration process.
A user goes to your site, signs up, and then you tell him you've sent him an email and he needs to verify his email address. So he hits Ctrl+T, pops open a new tab, hits his Gmail fav button, doesn't read a word of your lengthy welcome email, but clicks the first link he sees. Gmail opens your site in yet another tab...
He doesn't need nor want two tabs for your site open, he just wants to view that darn page you've disallowed him access to until he registers.
So what do we do? I saw one site (but I forget what it was) that did a really good job, and it actually refreshed the first tab I had open without me having to press anything.
I'm thinking, it might be nice if we can detect if the user already has a tab to your site open, we could either close the new verification-tab automatically, or tell him he can close it can go back to his other tab (which we've now refreshed and logged him in).
Or, maybe when he got your annoying "please check your email" message, he went directly to his email, replacing your site with his email knowing full well that the email will link him back to the site again. In that case, we don't want to close the tab, but maybe could have saved his location from before, and redirect him there again?
Anyway, that's just the use case... the question still stands. Can we detect if a user already has a tab to your site open?
This question is not about how to detect when a user has completed the sign-up process. Ajax polling or comet can solve that issue. I specifically want to know if the user already has a tab open to your site or not.
I'm fairly late to the party here (over a year), but I couldn't help but notice that you'd missed an incredibly easy and elegant solution (and probably what that website you saw used).
Using JavaScript you can change the name of the window you currently have open through:
window.name = "myWindow";
Then when you send out your confirmation email simply do (assuming you're sending a HTML email):
Verify
Which should result in the verificationLink opening up inside the window your website was already loaded into, if it's already been closed it'll open up a new tab with the window name specified.
You can stop the page functionality when user opened another tab or another window or even another browser
$(window).blur(function(){
// code to stop functioning or close the page
});
You can send an AJAX request every X seconds from the original tab that asks the server if it received a request from the email.
You cannot close the second tab automatically, but you could have it ask the server after 3X seconds whether it heard from the first tab.
What I have here is a little bit different use case to you but it detects if the site is being accessed in another tab. In this case I wanted to limit people using some call center pages to only one tab. It works well and is purely client-side.
// helper function to set cookies
function setCookie(cname, cvalue, seconds) {
var d = new Date();
d.setTime(d.getTime() + (seconds * 1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// helper function to get a cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
// Do not allow multiple call center tabs
if (~window.location.hash.indexOf('#admin/callcenter')) {
$(window).on('beforeunload onbeforeunload', function(){
document.cookie = 'ic_window_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
});
function validateCallCenterTab() {
var win_id_cookie_duration = 10; // in seconds
if (!window.name) {
window.name = Math.random().toString();
}
if (!getCookie('ic_window_id') || window.name === getCookie('ic_window_id')) {
// This means they are using just one tab. Set/clobber the cookie to prolong the tab's validity.
setCookie('ic_window_id', window.name, win_id_cookie_duration);
} else if (getCookie('ic_window_id') !== window.name) {
// this means another browser tab is open, alert them to close the tabs until there is only one remaining
var message = 'You cannot have this website open in multiple tabs. ' +
'Please close them until there is only one remaining. Thanks!';
$('html').html(message);
clearInterval(callCenterInterval);
throw 'Multiple call center tabs error. Program terminating.';
}
}
callCenterInterval = setInterval(validateCallCenterTab, 3000);
}
To flesh out John's answer, here is a working solution that uses plain JS and localStorage and updates the DOM with the count of the currently open tabs. Note that this solution detects the number of open tabs/windows for a given domain within one browser, but does not maintain the count across different browsers.
It uses the storage event to keep the count synchronized across all open tabs/windows without any need for refreshing the page.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
(function() {
var stor = window.localStorage;
window.addEventListener("load", function(e) {
var openTabs = stor.getItem("openTabs");
if (openTabs) {
openTabs++;
stor.setItem("openTabs", openTabs)
} else {
stor.setItem("openTabs", 1)
}
render();
})
window.addEventListener("unload", function(e) {
e.preventDefault();
var openTabs = stor.getItem("openTabs");
if (openTabs) {
openTabs--;
stor.setItem("openTabs", openTabs)
}
e.returnValue = '';
});
window.addEventListener('storage', function(e) {
render();
})
function render() {
var openTabs = stor.getItem("openTabs");
var tabnum = document.getElementById("tabnum");
var dname = document.getElementById("dname");
tabnum.textContent = openTabs;
dname.textContent = window.location.host
}
}());
</script>
</head>
<body>
<div style="width:100%;height:100%;text-align:center;">
<h1 >You Have<h1>
<h1 id="tabnum">0</h1>
<h1>Tab(s) of <span id="dname"></span> Open</h1>
</div>
</body>
</html>
To add to other answers:
You can also use localStorage. Have an entry like 'openedTabs'. When your page is opened, increase this number. When user leaves the page, decrease it.
The user will still have a session at the server. Why not store the user's location prior to registration, and when they confirm their registration, read the location back out of the session and redirect back to that page. No tab magic required. It's certainly not what I'd expect from a signup process.
It is possible to track number of tabs of your site opened by saving data in localstorage of each tab and counting the same, I created a github repository which can track number of tabs of your website a user has opened.
To use it Include tab-counter.js in your page and it will start tracking number of opened tabs.
console.log(tabCount.tabsCount());
Here's a system that uses broadcast channels for cross tab comms. It also assigns a unique ID per tab and manages the discovery of already opened tabs, for new tabs. Finally, using the ID as a stable index, it allows the user to rename their tabs. Tab closing events are handled via polling as well (unload events are unreliable).
This plugs into redux via the callbacks in the constructor. These are onNewTab, onDestroyTab, onRenameTab in this example.
import { setTabs } from './redux/commonSlice';
import { store } from './redux/store';
const promiseTimeout = (ms, promise) => {
let id;
let timeout = new Promise((resolve, reject) => {
id = setTimeout(() => {
reject('Timed out in ' + ms + 'ms.');
}, ms)
})
return Promise.race([
promise,
timeout
]).then((result) => {
clearTimeout(id);
return result;
})
};
// Promise that can be resolved/rejected outside of its constructor. Like a signal an async event has occured.
class DeferredPromise {
constructor() {
this._promise = new Promise((resolve, reject) => {
// assign the resolve and reject functions to `this`
// making them usable on the class instance
this.resolve = resolve;
this.reject = reject;
});
// bind `then` and `catch` to implement the same interface as Promise
this.then = this._promise.then.bind(this._promise);
this.catch = this._promise.catch.bind(this._promise);
this.finally = this._promise.finally.bind(this._promise);
this[Symbol.toStringTag] = 'Promise';
}
}
class TabManager {
tabCreateCallback = undefined;
tabDestroyCallback = undefined;
tabRenameCallback = undefined;
constructor(onNewTab, onDestroyTab, onRenameTab) {
this.tabCreateCallback = onNewTab.bind(this);
this.tabDestroyCallback = onDestroyTab.bind(this);
this.tabRenameCallback = onRenameTab.bind(this);
// creation time gives us a total ordering of open tabs, also acts as a tab ID
this.creationEpoch = Date.now();
this.channel = new BroadcastChannel("TabManager");
this.channel.onmessage = this.onMessage.bind(this);
// our current tab (self) counts too
this.tabs = [];
this.tabNames = {};
// start heartbeats. We check liveness like this as there is _no_ stable browser API for tab close.
// onbeforeunload is not reliable in all situations.
this.heartbeatPromises = {};
this.heartbeatIntervalMs = 1000;
setTimeout(this.doHeartbeat.bind(this), this.heartbeatIntervalMs);
}
doComputeNames() {
for (let i = 0; i < this.tabs.length; i++) {
const tab = this.tabs[i];
const name = this.tabNames[tab];
const defaultName = `Tab ${i + 1}`;
if (!name) {
this.tabNames[tab] = defaultName;
if (this.tabRenameCallback) {
this.tabRenameCallback(tab, name);
}
// if it's a default pattern but wrong inde value, rename it
} else if (name && this.isDefaultName(name) && name !== defaultName) {
this.tabNames[tab] = defaultName;
if (this.tabRenameCallback) {
this.tabRenameCallback(tab, name);
}
}
}
}
doHeartbeat() {
for (let tab of this.tabs) {
if (tab === this.creationEpoch) {
continue;
}
this.channel.postMessage({ type: "heartbeat_request", value: tab });
const heartbeatReply = new DeferredPromise();
heartbeatReply.catch(e => { });
// use only a fraction of poll interval to ensure timeouts occur before poll. Prevents spiral of death.
let heartbeatReplyWithTimeout = promiseTimeout(this.heartbeatIntervalMs / 3, heartbeatReply);
// destroy tab if heartbeat times out
heartbeatReplyWithTimeout.then(success => {
delete this.heartbeatPromises[tab];
}).catch(error => {
delete this.heartbeatPromises[tab];
this.tabs = this.tabs.filter(id => id !== tab);
this.tabs.sort();
this.doComputeNames();
if (this.tabDestroyCallback) {
this.tabDestroyCallback(tab);
}
});
this.heartbeatPromises[tab] = heartbeatReply;
}
// re-schedule to loop again
setTimeout(this.doHeartbeat.bind(this), this.heartbeatIntervalMs);
}
doInitialize() {
this.tabs = [this.creationEpoch];
this.doComputeNames();
if (this.tabCreateCallback) {
this.tabCreateCallback(this.creationEpoch);
}
this.channel.postMessage({ type: "creation", value: this.creationEpoch });
}
onMessage(event) {
if (event.data.type == "creation") {
const newTabId = event.data.value;
// add the new tab
if (!this.tabs.includes(newTabId)) {
this.tabs.push(newTabId);
this.tabs.sort();
this.doComputeNames();
if (this.tabCreateCallback) {
this.tabCreateCallback(newTabId);
}
}
// send all of the tabs we know about to it
this.channel.postMessage({ type: "syncnew", value: this.tabs });
// those tabs we just sent might already have custom names, lets send the older rename requests
// which would have had to have occured. I.E. lets replay forward time and sync the states of ours to theirs.
for (let tab of this.tabs) {
const name = this.tabNames[tab];
if (name && !this.isDefaultName(name)) {
this.notifyTabRename(tab, name);
}
}
} else if (event.data.type == "syncnew") {
let newTabs = [];
// just got a list of new tabs add them if we down't know about them
for (let id of event.data.value) {
if (!this.tabs.includes(id)) {
newTabs.push(id);
}
}
// merge the lists and notify of only newly discovered
if (newTabs.length) {
this.tabs = this.tabs.concat(newTabs);
this.tabs.sort();
this.doComputeNames();
for (let id of newTabs) {
if (this.tabCreateCallback) {
this.tabCreateCallback(id);
}
}
}
} else if (event.data.type == "heartbeat_request") {
// it's for us, say hi back
if (event.data.value === this.creationEpoch) {
this.channel.postMessage({ type: "heartbeat_reply", value: this.creationEpoch });
}
} else if (event.data.type == "heartbeat_reply") {
// got a reply, cool resolve the heartbeat
if (this.heartbeatPromises[event.data.value]) {
// try catch since this is racy, entry may have timed out after this check passed
try {
this.heartbeatPromises[event.data.value].resolve();
} catch {
}
}
} else if (event.data.type == "rename") {
// someone renamed themselves, lets update our record
const { id, name } = event.data.value;
if (this.tabs.includes(id)) {
this.tabNames[id] = name;
// first original (potentially illegal) rename callback first
if (this.tabRenameCallback) {
this.tabRenameCallback(id, name);
}
// force tab numbers back to consistent
this.doComputeNames();
}
}
}
setTabName(id, name) {
if (this.tabs.includes(id)) {
this.tabNames[id] = name;
this.notifyTabRename(id, name);
if (this.tabRenameCallback) {
this.tabRenameCallback(id, name);
}
// force tab numbers back to consistent
this.doComputeNames();
}
}
notifyTabRename(id, name) {
this.channel.postMessage({ type: "rename", value: { id, name } });
}
isDefaultName(name) {
return name.match(/Tab [0-9]+/)
}
getMyTabId() {
return this.creationEpoch;
}
getMyTabIndex() {
return this.tabs.findIndex(tab => tab === this.creationEpoch);
}
isMyTab(id) {
return id === this.creationEpoch;
}
getAllTabs() {
return this.tabs.map((tab, idx) => {
return { id: tab, index: idx, name: this.tabNames[tab] ?? "" };
}, this);
}
}
function onDestroyTab(id) {
store.dispatch(setTabs(this.getAllTabs()));
console.log(`Tab ${id} destroyed`);
}
function onNewTab(id) {
store.dispatch(setTabs(this.getAllTabs()));
console.log(`Tab ${id} created`);
}
function onRenameTab(id, name) {
store.dispatch(setTabs(this.getAllTabs()));
console.log(`Tab ${id} renamed to ${name}`);
}
const TabManager = new TabManager(onNewTab, onDestroyTab, onRenameTab);
export default TabManager;
Initialize it on page load
window.addEventListener("DOMContentLoaded", function (event) {
TabManager.doInitialize();
});
Access any of the methods on the static object at any time. Note that you can get rename events out of order from create / destroy. This could be resolved, but it wasn't important for me.

Event when window.location.href changes

I'm writing a Greasemonkey script for a site which at some point modifies location.href.
How can I get an event (via window.addEventListener or something similar) when window.location.href changes on a page? I also need access to the DOM of the document pointing to the new/modified url.
I've seen other solutions which involve timeouts and polling, but I'd like to avoid that if possible.
I use this script in my extension "Grab Any Media" and work fine ( like youtube case )
var oldHref = document.location.href;
window.onload = function() {
var bodyList = document.querySelector("body")
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (oldHref != document.location.href) {
oldHref = document.location.href;
/* Changed ! your code here */
}
});
});
var config = {
childList: true,
subtree: true
};
observer.observe(bodyList, config);
};
With the latest javascript specification
const observeUrlChange = () => {
const oldHref = document.location.href;
const body = document.querySelector("body");
const observer = new MutationObserver(mutations => {
mutations.forEach(() => {
if (oldHref !== document.location.href) {
oldHref = document.location.href;
/* Changed ! your code here */
}
});
});
observer.observe(body, { childList: true, subtree: true });
};
window.onload = observeUrlChange;
Compressed with OpenAI
window.onload = () => new MutationObserver(mutations => mutations.forEach(() => oldHref !== document.location.href && (oldHref = document.location.href, /* Changed ! your code here */))).observe(document.querySelector("body"), { childList: true, subtree: true });
popstate event:
The popstate event is fired when the active history entry changes. [...] The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript)
So, listening to popstate event and sending a popstate event when using history.pushState() should be enough to take action on href change:
window.addEventListener('popstate', listener);
const pushUrl = (href) => {
history.pushState({}, '', href);
window.dispatchEvent(new Event('popstate'));
};
You can't avoid polling, there isn't any event for href change.
Using intervals is quite light anyways if you don't go overboard. Checking the href every 50ms or so will not have any significant effect on performance if you're worried about that.
There is a default onhashchange event that you can use.
Documented HERE
And can be used like this:
function locationHashChanged( e ) {
console.log( location.hash );
console.log( e.oldURL, e.newURL );
if ( location.hash === "#pageX" ) {
pageX();
}
}
window.onhashchange = locationHashChanged;
If the browser doesn't support oldURL and newURL you can bind it like this:
//let this snippet run before your hashChange event binding code
if( !window.HashChangeEvent )( function() {
let lastURL = document.URL;
window.addEventListener( "hashchange", function( event ) {
Object.defineProperty( event, "oldURL", { enumerable: true, configurable: true, value: lastURL } );
Object.defineProperty( event, "newURL", { enumerable: true, configurable: true, value: document.URL } );
lastURL = document.URL;
} );
} () );
Through Jquery, just try
$(window).on('beforeunload', function () {
//your code goes here on location change
});
By using javascript:
window.addEventListener("beforeunload", function (event) {
//your code goes here on location change
});
Refer Document : https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
Have you tried beforeUnload?
This event fires immediately before the page responds to a navigation request, and this should include the modification of the href.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<META NAME="Generator" CONTENT="TextPad 4.6">
<META NAME="Author" CONTENT="?">
<META NAME="Keywords" CONTENT="?">
<META NAME="Description" CONTENT="?">
</HEAD>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(window).unload(
function(event) {
alert("navigating");
}
);
$("#theButton").click(
function(event){
alert("Starting navigation");
window.location.href = "http://www.bbc.co.uk";
}
);
});
</script>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#FF0000" VLINK="#800000" ALINK="#FF00FF" BACKGROUND="?">
<button id="theButton">Click to navigate</button>
Google
</BODY>
</HTML>
Beware, however, that your event will fire whenever you navigate away from the page, whether this is because of the script, or somebody clicking on a link.
Your real challenge, is detecting the different reasons for the event being fired. (If this is important to your logic)
Try this script which will let you run code whenever the URL changes (without a pageload, like an Single Page Application):
var previousUrl = '';
var observer = new MutationObserver(function(mutations) {
if (location.href !== previousUrl) {
previousUrl = location.href;
console.log(`URL changed to ${location.href}`);
}
});
based on the answer from "Leonardo Ciaccio", modified code is here:
i.e. removed for loop and reassign the Body Element if it is removed
window.addEventListener("load", function () {
let oldHref = document.location.href,
bodyDOM = document.querySelector("body");
function checkModifiedBody() {
let tmp = document.querySelector("body");
if (tmp != bodyDOM) {
bodyDOM = tmp;
observer.observe(bodyDOM, config);
}
}
const observer = new MutationObserver(function (mutations) {
if (oldHref != document.location.href) {
oldHref = document.location.href;
console.log("the location href is changed!");
window.requestAnimationFrame(checkModifiedBody)
}
});
const config = {
childList: true,
subtree: true
};
observer.observe(bodyDOM, config);
}, false);
Well there is 2 ways to change the location.href. Either you can write location.href = "y.html", which reloads the page or can use the history API which does not reload the page. I experimented with the first a lot recently.
If you open a child window and capture the load of the child page from the parent window, then different browsers behave very differently. The only thing that is common, that they remove the old document and add a new one, so for example adding readystatechange or load event handlers to the old document does not have any effect. Most of the browsers remove the event handlers from the window object too, the only exception is Firefox. In Chrome with Karma runner and in Firefox you can capture the new document in the loading readyState if you use unload + next tick. So you can add for example a load event handler or a readystatechange event handler or just log that the browser is loading a page with a new URI. In Chrome with manual testing (probably GreaseMonkey too) and in Opera, PhantomJS, IE10, IE11 you cannot capture the new document in the loading state. In those browsers the unload + next tick calls the callback a few hundred msecs later than the load event of the page fires. The delay is typically 100 to 300 msecs, but opera simetime makes a 750 msec delay for next tick, which is scary. So if you want a consistent result in all browsers, then you do what you want to after the load event, but there is no guarantee the location won't be overridden before that.
var uuid = "win." + Math.random();
var timeOrigin = new Date();
var win = window.open("about:blank", uuid, "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
var callBacks = [];
var uglyHax = function (){
var done = function (){
uglyHax();
callBacks.forEach(function (cb){
cb();
});
};
win.addEventListener("unload", function unloadListener(){
win.removeEventListener("unload", unloadListener); // Firefox remembers, other browsers don't
setTimeout(function (){
// IE10, IE11, Opera, PhantomJS, Chrome has a complete new document at this point
// Chrome on Karma, Firefox has a loading new document at this point
win.document.readyState; // IE10 and IE11 sometimes fails if I don't access it twice, idk. how or why
if (win.document.readyState === "complete")
done();
else
win.addEventListener("load", function (){
setTimeout(done, 0);
});
}, 0);
});
};
uglyHax();
callBacks.push(function (){
console.log("cb", win.location.href, win.document.readyState);
if (win.location.href !== "http://localhost:4444/y.html")
win.location.href = "http://localhost:4444/y.html";
else
console.log("done");
});
win.location.href = "http://localhost:4444/x.html";
If you run your script only in Firefox, then you can use a simplified version and capture the document in a loading state, so for example a script on the loaded page cannot navigate away before you log the URI change:
var uuid = "win." + Math.random();
var timeOrigin = new Date();
var win = window.open("about:blank", uuid, "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
var callBacks = [];
win.addEventListener("unload", function unloadListener(){
setTimeout(function (){
callBacks.forEach(function (cb){
cb();
});
}, 0);
});
callBacks.push(function (){
console.log("cb", win.location.href, win.document.readyState);
// be aware that the page is in loading readyState,
// so if you rewrite the location here, the actual page will be never loaded, just the new one
if (win.location.href !== "http://localhost:4444/y.html")
win.location.href = "http://localhost:4444/y.html";
else
console.log("done");
});
win.location.href = "http://localhost:4444/x.html";
If we are talking about single page applications which change the hash part of the URI, or use the history API, then you can use the hashchange and the popstate events of the window respectively. Those can capture even if you move in history back and forward until you stay on the same page. The document does not changes by those and the page is not really reloaded.
ReactJS and other SPA applications use the history object
You can listen to window.history updating with the following code:
function watchHistoryEvents() {
const { pushState, replaceState } = window.history;
window.history.pushState = function (...args) {
pushState.apply(window.history, args);
window.dispatchEvent(new Event('pushState'));
};
window.history.replaceState = function (...args) {
replaceState.apply(window.history, args);
window.dispatchEvent(new Event('replaceState'));
};
window.addEventListener('popstate', () => console.log('popstate event'));
window.addEventListener('replaceState', () => console.log('replaceState event'));
window.addEventListener('pushState', () => console.log('pushState event'));
}
watchHistoryEvents();

Categories