Do browsers propagate javascript variables across

2019-08-20 15:22发布

问题:

I have some JavaScript that will look to see if a var is set, if it is set then do something if not don't.

if (reset === 'reset') {
    gallery.unformat(container);
}

reset is only set once the page has loaded. So this script will only execute after the user reloads the page.

If i open a new tab in firefox reset isn't set. If i open a new tab in chrome reset is set.

So for my case chrome handles it correctly and only on the first going to the site does this var get set and thus everything works correctly.

I want to know is do variables propagate across tabs and if so which browsers do what?

回答1:

Variables should not persist across new tabs. I can't reproduce the behaviour you see in Chrome.

You should looking at using cookies, or if you want to be HTML5, look at localStorage.

Both of these are domain specific, rather than per-tab.

E.g. in localStorage, you could go for;

// Check that localStorage is supported in the current browser, and then try
// to retrieve the item.
if ('localStorage' in window && localStorage.getItem('reset') === 'reset') {
    gallery.unformat(container);
}

You'd then be able to set reset later via;

localStorage.setItem('reset', 'reset');


回答2:

No, variable values should not propagate between tabs - each tab should have its own global namespace, there would be all kinds of security issues if one tab could affect the JavaScript in another.