If I open an app (SPA) in multiple tabs (manually opened tabs), I want to make some of the information persistent as a session for each tab. Session storage does this job.
But when I right click on an anchor and then select “open in new tab” in specific tab, I want to pass that session storage into the new opened tab.
The local storage does not work for this, because I want each tab to hold independent data, but those tabs that are opened from another tab to access the opener data.
There should be a place to keep a data in each tab, where:
- Tabs that are opened from another tab, to have access to that opener place
- Tabs that are manually opened to not be able to read data from that place
When I middle-click with the mouse on the refresh button of the browser, It opens a new tab and passes the session storage from the current tab into the new opened tab. I want something like this to happen when I right click and select “open in new tab” on an anchor.
How I can achieve this behaviour?
Without adding information to the link URL/query params
4
You can use window.name
and sessionStorage
together.
Set data in window.name
for the new tab:
function openTabWithData(url) {
const data = sessionStorage.getItem('key');
const newTab = window.open(url, '_blank');
newTab.onload = function() {
newTab.name = data
}
}
Retrieve the data in the new tab and store it in sessionStorage
:
window.addEventListener('load', function() {
if (window.name) {
sessionStorage.setItem('key', window.name);
window.name = '';
}
});
Example usage:
<a href="javascript:void(0);" onclick="openTabWithData('myNewTab.html')">Open in New Tab</a>
-
Each tab has its own session data
-
Tabs opened from another tab can access the shared data
-
Tabs manually opened don’t have access to the data.
2