I am trying to create something that automatically clicks the required buttons on stackexchange type sites so that I can stop doing it myself. I am using a content script. I am trying to:
Find the button to customize cookies
click accept (they're usually all deselected with stackexchange sites)
Here is my code so far. I think it finds the right node, but clicks it too soon? I am not entirely sure since I'm new to js and whatnot.
function AcceptCustomization() {
let myNode;
let observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (!mutation.addedNodes) return
for (let i = 0; i < mutation.addedNodes.length; i++) {
// do things to your newly added nodes here
let node = mutation.addedNodes[i]
if (node.nodeType === 1) {
node
var a = node.getElementsByClassName("flex--item s-btn s-btn__primary save-preference-btn-handler onetrust-close-btn-handler js-consent-banner-hide js-consent-save")[0]
if (a) {
myNode = a
console.log(myNode)
console.log(myNode.click())
}
}
}
})
})
observer.observe(document.body, {
childList: true
, subtree: true
, attributes: false
, characterData: false
})
}
function CustomizeCookies() {
var a = document.getElementsByClassName("flex--item s-btn s-btn__filled js-cookie-settings")[0];
if (a) {
a.click();
AcceptCustomization();
}
else {
console.log(a);
}
}
CustomizeCookies();
In the future, I want to create an extension that I can use to create a sort of database of websites with corresponding button clicks. For example, if I don't have the cookie customization for a website, I would click the extension and run a script that captures my button clicks and redoes them every future time I visit (if it is not the same session).
Thanks :)
I am trying to get this chrome storage sync set to run when the person closes the popup window in my chrome extension but cannot seem to get it working. That way if they abruptly close the extension window say by clicking in their browser or whatever their data still stores. Anyone have any ideas?
window.addEventListener("beforeunload", function load(unloadEvent) {
let currentTimeGet = document.getElementById("currentTimeInfo").innerHTML;
chrome.storage.sync.set({ ct: currentTimeGet }, function() {
console.log("Value is set to " + currentTimeGet);
});
});
beforeunload event is ignored for the popup shown by browser_action or page_action.
unload won't wait for the asynchronous chrome.storage to complete so the data won't be stored
Based on this several solutions are possible.
Autosave on any change.
This is the preferable and modern user-friendly solution. You can give the elements an id that's equal to their name in chrome.storage like <input type="text" id="userName" class="storage">.
const STORAGE_SELECTOR = '.storage[id]';
let debounceTimer;
document.addEventListener('change', saveOnChange);
document.addEventListener('input', saveOnChange);
function saveOnChange(e) {
if (e.target.closest(STORAGE_SELECTOR)) {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(doSave, 100);
}
}
function collectData() {
const data = {};
for (const el of document.querySelectorAll(STORAGE_SELECTOR))
data[el.id] = el.type === 'checkbox' ? el.checked : el.value;
return data;
}
As for doSave() function, either simply overwrite the current options data in storage
function doSave() {
chrome.storage.sync.set(collectData());
}
or save under a separate autoSave and check it the next time the popup is shown:
function doSave() {
chrome.storage.sync.set({autoSave: collectData()});
}
function loadFromStorage() {
chrome.storage.sync.get(data => {
if (data.autoSave) data = data.autoSave;
for (const [id, value] of Object.entries(data)) {
const el = document.getElementById(id);
if (el) el[el.type === 'checkbox' ? 'checked' : 'value'] = value;
}
});
}
loadFromStorage();
Save the data in unload event directly in the backround script's JavaScript window object e.g. chrome.extension.getBackgroundPage().popupData = collectData().
It's bad because it requires a persistent background page (or a temporarily persistent page) and because Chrome moves away from unload events in general. The data may be easily lost on a crash of the extension process or of the browser itself, it might be lost if the browser was closed by the user.
I'm having two pages: my-view1 and my-view2.
On my-view1 I have two buttons that add and remove data from LocalStorage.
On my-view2 I have two simple div's that READ (display) total value, and total in last 6 months value.
However, on the second page, the value will not update if the page is not refreshed. I want the values from my-view2 to be automatically updated everytime the page is loaded (viewed, even if cached).
Here is a plnkr with my-view2 so you can undestrand what I'm trying to do.
https://plnkr.co/edit/ul4T2mduxjElCN4rUUKd?p=info
How can I do this?
You can listen to the storage event to trigger and update some prop in my-view2 when you update localStorage:
<my-view-2 id="myView2"></my-view-2>
<script>
window.onstorage = function(e) {
if (e.key !== 'someKeyYouWant') return;
document.getElementById('myView2').set('someProp', {
oldValue: e.oldValue,
newValue: e.newValue
});
};
</script>
EDIT (working plunk): Because of a behavior described here the storage event will not be triggered on the window originating the change, so you have to trigger your own storage event, consider the method below:
saveToLs(e) {
e.preventDefault();
const newName = this.get('dogName');
const ls = window.localStorage;
const synthEvent = new StorageEvent('storage');
const eventConfig = [
'storage',
true,
true,
'myDog',
ls.getItem('myDog'),
newName
];
synthEvent.initStorageEvent(...eventConfig);
setTimeout((() => { // ensure async queue
ls.setItem('myDog', newName);
this.dispatchEvent(synthEvent);
}).bind(this), 0);
}
...and on the listening side:
handleStorageUpdate(e) {
if (e.key !== 'myDog' || e.newValue === this.get('dogName')) return;
this.set('dogName', e.newValue);
}
Please note the if conditional handling potential duplicate updates with the same value.
Here is a working plunk for you to play with
I am using Google invisible recaptcha. Is there a way to detect when the challenge window is closed? By challenge window I mean window where you have to pick some images for verification.
I currently put a spinner on the button that rendered the recaptcha challenge, once the button is clicked. There is no way for the user to be prompted with another challenge window.
I am calling render function programmatically:
grecaptcha.render(htmlElement, { callback: this.verified, expiredCallback: this.resetRecaptcha, sitekey: this.siteKey, theme: "light", size: "invisible" });
I have 2 callback functions wired up the verified and the resetRecaptcha functions which look like:
function resetRecaptcha() {
grecaptcha.reset();
}
function verified(recaptchaResponse)
{
/*
which calls the server to validate
*/
}
I would have expected that grecaptcha.render has another callback that is called when the challenge screen is closed without the user verifying himself by selecting the images.
As you mention, the API doesn't support this feature.
However, you can add this feature yourself. You may use the following code with caution, Google might change its reCaptcha and by doing so break this custom code. The solution relies on two characteristics of reCaptcha, so if the code doesn't work, look there first:
the window iframe src: contains "google.com/recaptcha/api2/bframe"
the CSS opacity property: changed to 0 when the window is closed
// to begin: we listen to the click on our submit button
// where the invisible reCaptcha has been attachtted to
// when clicked the first time, we setup the close listener
recaptchaButton.addEventListener('click', function(){
if(!window.recaptchaCloseListener) initListener()
})
function initListener() {
// set a global to tell that we are listening
window.recaptchaCloseListener = true
// find the open reCaptcha window
HTMLCollection.prototype.find = Array.prototype.find
var recaptchaWindow = document
.getElementsByTagName('iframe')
.find(x=>x.src.includes('google.com/recaptcha/api2/bframe'))
.parentNode.parentNode
// and now we are listening on CSS changes on it
// when the opacity has been changed to 0 we know that
// the window has been closed
new MutationObserver(x => recaptchaWindow.style.opacity == 0 && onClose())
.observe(recaptchaWindow, { attributes: true, attributeFilter: ['style'] })
}
// now do something with this information
function onClose() {
console.log('recaptcha window has been closed')
}
As I mentioned in the comments of the answer submitted by #arcs, it is a good solution which works but it also fires onClose() when the user successfully completes the challenge. My solution is to change the onClose() function like so:
// now do something with this information
function onClose() {
if(!grecaptcha.getResponse()) {
console.log('recaptcha window has been closed')
}
}
This way, it only executes the desired code if the challenge has been closed and it has not been completed by the user, thus the response cannot be returned with grecaptcha.getResponse()
The drawback of detecting when iframe was hidden is that it fires not only when user closes captcha by clicking in background, but also when he submits the answer.
What I needed is detect only the first situation (cancel captcha).
I created a dom observer to detect when captcha is attached to DOM, then I disconnect it (because it is no longer needed) and add click handler to its background element.
Keep in mind that this solution is sensitive to any changes in DOM structure, so if google decides to change it for whatever reason, it may break.
Also remember to cleanup the observers/listeners, in my case (react) I do it in cleanup function of useEffect.
const captchaBackgroundClickHandler = () => {
...do whatever you need on captcha cancel
};
const domObserver = new MutationObserver(() => {
const iframe = document.querySelector("iframe[src^=\"https://www.google.com/recaptcha\"][src*=\"bframe\"]");
if (iframe) {
domObserver.disconnect();
captchaBackground = iframe.parentNode?.parentNode?.firstChild;
captchaBackground?.addEventListener("click", captchaBackgroundClickHandler);
}
});
domObserver.observe(document.documentElement || document.body, { childList: true, subtree: true });
To work in IE this solution needs polyfills for .include() and Array.from(), found below:
Array.from on the Internet Explorer
ie does not support 'includes' method
And the updated code:
function initListener() {
// set a global to tell that we are listening
window.recaptchaCloseListener = true
// find the open reCaptcha window
var frames = Array.from(document.getElementsByTagName('iframe'));
var recaptchaWindow;
frames.forEach(function(x){
if (x.src.includes('google.com/recaptcha/api2/bframe') ){
recaptchaWindow = x.parentNode.parentNode;
};
});
// and now we are listening on CSS changes on it
// when the opacity has been changed to 0 we know that
// the window has been closed
new MutationObserver(function(){
recaptchaWindow.style.opacity == 0 && onClose();
})
.observe(recaptchaWindow, { attributes: true, attributeFilter: ['style'] })
}
My solution:
let removeRecaptchaOverlayEventListener = null
const reassignGRecatchaExecute = () => {
if (!window.grecaptcha || !window.grecaptcha.execute) {
return
}
/* save original grecaptcha.execute */
const originalExecute = window.grecaptcha.execute
window.grecaptcha.execute = (...params) => {
try {
/* find challenge iframe */
const recaptchaIframe = [...document.body.getElementsByTagName('iframe')].find(el => el.src.match('https://www.google.com/recaptcha/api2/bframe'))
const recaptchaOverlay = recaptchaIframe.parentElement.parentElement.firstElementChild
/* detect when the recaptcha challenge window is closed and reset captcha */
!removeRecaptchaOverlayEventListener && recaptchaOverlay.addEventListener('click', window.grecaptcha.reset)
/* save remove event listener for click event */
removeRecaptchaOverlayEventListener = () => recaptchaOverlay.removeEventListener('click', window.grecaptcha.reset)
} catch (error) {
console.error(error)
} finally {
originalExecute(...params)
}
}
}
Call this function after you run window.grecaptcha.render() and before window.grecaptcha.execute()
And don't forget to remove event listener: removeRecaptchaOverlayEventListener()
For everybody that didn't quite get how it all works, here is another example with explanations that you might find useful:
So we have 2 challenges here.
1) Detect when the challenge is shown and get the overlay div of the challenge
function detectWhenReCaptchaChallengeIsShown() {
return new Promise(function(resolve) {
const targetElement = document.body;
const observerConfig = {
childList: true,
attributes: false,
attributeOldValue: false,
characterData: false,
characterDataOldValue: false,
subtree: false
};
function DOMChangeCallbackFunction(mutationRecords) {
mutationRecords.forEach((mutationRecord) => {
if (mutationRecord.addedNodes.length) {
var reCaptchaParentContainer = mutationRecord.addedNodes[0];
var reCaptchaIframe = reCaptchaParentContainer.querySelectorAll('iframe[title*="recaptcha"]');
if (reCaptchaIframe.length) {
var reCaptchaChallengeOverlayDiv = reCaptchaParentContainer.firstChild;
if (reCaptchaChallengeOverlayDiv.length) {
reCaptchaObserver.disconnect();
resolve(reCaptchaChallengeOverlayDiv);
}
}
}
});
}
const reCaptchaObserver = new MutationObserver(DOMChangeCallbackFunction);
reCaptchaObserver.observe(targetElement, observerConfig);
});
}
First, we created a target element that we would observe for Google iframe appearance. We targeted document.body as an iframe will be appended to it:
const targetElement = document.body;
Then we created a config object for MutationObserver. Here we might specify what exactly we track in DOM changes. Please note that all values are 'false' by default so we could only leave 'childList' - which means that we would observe only the child node changes for the target element - document.body in our case:
const observerConfig = {
childList: true,
attributes: false,
attributeOldValue: false,
characterData: false,
characterDataOldValue: false,
subtree: false
};
Then we created a function that would be invoked when an observer detects a specific type of DOM change that we specified in config object. The first argument represents an array of Mutation Observer objects. We grabbed the overlay div and returned in with Promise.
function DOMChangeCallbackFunction(mutationRecords) {
mutationRecords.forEach((mutationRecord) => {
if (mutationRecord.addedNodes.length) { //check only when notes were added to DOM
var reCaptchaParentContainer = mutationRecord.addedNodes[0];
var reCaptchaIframe = reCaptchaParentContainer.querySelectorAll('iframe[title*="recaptcha"]');
if (reCaptchaIframe.length) { // Google reCaptcha iframe was loaded
var reCaptchaChallengeOverlayDiv = reCaptchaParentContainer.firstChild;
if (reCaptchaChallengeOverlayDiv.length) {
reCaptchaObserver.disconnect(); // We don't want to observe more DOM changes for better performance
resolve(reCaptchaChallengeOverlayDiv); // Returning the overlay div to detect close events
}
}
}
});
}
Lastly we instantiated an observer itself and started observing DOM changes:
const reCaptchaObserver = new MutationObserver(DOMChangeCallbackFunction);
reCaptchaObserver.observe(targetElement, observerConfig);
2) Second challenge is the main question of that post - how do we detect that the challenge is closed? Well, we need help of MutationObserver again.
detectReCaptchaChallengeAppearance().then(function (reCaptchaChallengeOverlayDiv) {
var reCaptchaChallengeClosureObserver = new MutationObserver(function () {
if ((reCaptchaChallengeOverlayDiv.style.visibility === 'hidden') && !grecaptcha.getResponse()) {
// TADA!! Do something here as the challenge was either closed by hitting outside of an overlay div OR by pressing ESC key
reCaptchaChallengeClosureObserver.disconnect();
}
});
reCaptchaChallengeClosureObserver.observe(reCaptchaChallengeOverlayDiv, {
attributes: true,
attributeFilter: ['style']
});
});
So what we did is we get the Google reCaptcha challenge overlay div with the Promise we created in Step1 and then we subscribed for "style" changes on overlay div. This is because when the challenge is closed - Google fade it out.
It's important to note that the visibility will be also hidden when a person solves the captcha successfully. That is why we added !grecaptcha.getResponse() check. It will return nothing unless the challenge is resolved.
This is pretty much it - I hope that helps :)
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.