Created
January 16, 2019 13:01
-
-
Save J-Cake/98c30d729b87ce0343ffa7e40d33698f to your computer and use it in GitHub Desktop.
How to only have one instance of a window open while feeding info into it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let isMainWindow = false; // keep track of main instance. | |
// Of course the main instance should be kept track of in a better way than this, perhaps find a way of uniquely identifying the tabs | |
// and storing the ID of the active tab in localStorage. | |
window.addEventListener('load', e => { | |
if (!window.localStorage.mainWindowVacant) window.localStorage.mainWindowVacant = "true"; // initialsise window.localStorage | |
if (!window.localStorage.openInstances) window.localStorage.mainWindowVacant = "true"; // initialsise window.localStorage | |
if (window.localStorage.mainWindowVacant !== "false") { | |
// Take Over Main Instance | |
isMainWindow = true; | |
window.localStorage.mainWindowVacant = "false"; | |
watchInstance(); | |
} else { // can't take over main window | |
window.localStorage.openInstances += (document.querySelector('.name').value || "untitled") + ", "; | |
//exit | |
window.closeHandler(); | |
alert('closing'); | |
} | |
}) | |
window.addEventListener('unload', closeHandler); // listen for a close event and vacate main position | |
function closeHandler() { | |
if (isMainWindow) { | |
window.localStorage.mainWindowVacant = "true"; // this "vacates" the main window position allowing another tab to take the main window's place. ie the main window has been closed. | |
} | |
} | |
async function watchInstance() { | |
let prevAmnt = window.localStorage.openInstances; | |
setInterval(e => { | |
if (window.localStorage.openInstances !== prevAmnt) { | |
// do some logic once the openInstances updates (ie a new tab has been opened and is ready to be migrated to main tab) | |
showOpenInstances(); | |
} | |
}, 1) | |
} | |
async function showOpenInstances() { | |
// just a function that provides feedback to the user once a new tab has been opened. | |
// use this function to update the tabs list and load other stuff. | |
// Put some kind of logic here that will focus the window. If that's even possible. | |
const instances = window.localStorage.openInstances.split(', '); | |
document.querySelector('.body').innerHTML = instances.reduce((a, i) => a + i + "<br />"); | |
} | |
// @RahulJain |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment