问题
I have two browser windows A and B open side by side.
When someone clicks a button in window A I want to run a function in window B.
I’m currently using the hashchange event in window B and the window.open(myurl,myurl) in window A to tell the other window to start running the function, but this doesn’t work very well when the url changes.
Is there another solution in javascript to init events outside the current window?
回答1:
One way I can think of is to provoke a localStorage change that the other tab/window will detect, as long as both belong to the same domain, thus sharing the same localStorage. If in your event triggering tab you do something like this:
localStorage.setItem('detectMyChange', '0');
localStorage.setItem('detectMyChange', '1');
Then you can detect that change on the other tab/window and react to it (I´m using JQuery here, is similar with pure Javascript):
$(window).on('storage', function (e) {
var storageEvent = e.originalEvent;
if ((storageEvent.key == 'detectMyChange') && (storageEvent.oldValue == '0') && (storageEvent.newValue == '1')) {
// Event detected, do some really useful thing here ;)
}
});
The reason for changing the localStorage twice in the triggering window is to be able to trigger the event again (in the same window or other) using the same code, because you detect the change of the localStorage variable from one known value to another known value.
You can even set different new values to send different information to the other tabs/window. Hope it helps.
来源:https://stackoverflow.com/questions/38151785/jquery-fire-event-in-other-tab-window