jQuery: Fire event in other tab/window

百般思念 提交于 2019-12-12 01:45:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!