Skip to content

Instantly share code, notes, and snippets.

@maateusilva
Last active November 26, 2021 19:38
Show Gist options
  • Save maateusilva/7e832d572c60a46ef3883d6413d3da10 to your computer and use it in GitHub Desktop.
Save maateusilva/7e832d572c60a46ef3883d6413d3da10 to your computer and use it in GitHub Desktop.
JavaScript Snippet to detect when tab is closed
// Get or Create a new tab id (accessible only on the tab itself)
var tabID = sessionStorage.tabID ? sessionStorage.tabID : sessionStorage.tabID = Math.random();
// Get all connected tabs from localStorage (shared between all tabs)
var connectedTabs = localStorage.getItem("ConnectedTabs");
// Validate if tabID was created
if (tabID) {
if (!connectedTabs) {
// If there's no tabs connected yet, create an array with itself tabID
var tabs = [tabID];
} else {
// Parse the tabs array
connectedTabs = JSON.parse(connectedTabs);
// Check if this tab is already added in connections array
var alreadyAdded = connectedTabs.indexOf(tabID);
// Push the new tabID to array of tabs only if it was not added yet
if (alreadyAdded < 0) {
connectedTabs.push(tabID);
}
var tabs = connectedTabs;
}
// Save the JSON
localStorage.setItem("ConnectedTabs", JSON.stringify(tabs));
}
// Create a new listener to trigger when tab is closed
window.addEventListener("beforeunload", function (e) {
// Get tabs in storage
var connectedTabs = localStorage.getItem("ConnectedTabs");
// If it's everything okay in tabs retrieve...
if (connectedTabs) {
// Parse the tabs array again
connectedTabs = JSON.parse(connectedTabs);
// If there's only one tab connected remove the storage position
if (connectedTabs.length === 1) {
localStorage.removeItem("ConnectedTabs");
} else { // But if have more than one tab connected...
// Find the position of our tab by her tabID in storage
var currentTab = connectedTabs.indexOf(tabID);
// Remove the tab from our storage list
connectedTabs.splice(currentTab, 1);
// Save our updated list keeping only connected tabs
localStorage.setItem("ConnectedTabs", JSON.stringify(connectedTabs));
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment