There are several approaches which enable you to persist data and / or state between pages on your website, which include:
- Cookies (Old school. Can be read on the client-side or on the server-side)
- the Query String (a
?
followed bykeys
andvalues
at the end of the URL) - the Hash Fragment (a
#
followed by a string at the end of the URL)
But probably the cleanest and most straightforward approach is:
WebStorage
(which includes two variants:localStorage
andsessionStorage
)
Given the setup you describe above, you might have each key-value entry in your localStorage
describe a tab and a URL:
'Tab1' | '/tab1.html'
'Tab2' | '/tab2.html'
'Tab4' | '/tab4.html'
This means that when a user clicks on a Tab 1 button:
// Grab tab1Button in DOM
const tab1Button = document.getElementById('tab1Button');
// Reusable function to create tabs
function createTab() {
// OTHER CODE
localStorage.setItem('Tab1', '/tab1.html');
}
// Event Listener which activates function when user clicks corresponding button
tab1Button.addEventListener('click', createTab, false);
Then, on page load, Javascript will be able to interrogate the localStorage
like this:
const myBar = document.getElementById('bar');
// Check 'Tab1' Entry exists
if (localStorage.get('Tab1') !== null) {
// Create Tab
const tab1Div = document.createElement('div');
tab1Div.id = 'tab1Div';
// Create Tab Link
const tab1Link = document.createElement('a');
tab1Link.setAttribute('href', localStorage.get('Tab1'));
tab1Link.textContent = 'Redirect';
// Add Tab Link to Tab
tab1Div.appendChild(tab1Link);
// Add Tab to DOM
myBar.appendChild(tab1Div);
}
Further Reading:
- Using the Web Storage API by MDN