jQuery:在其他选项卡/窗口中触发事件
我有两个同时打开的浏览器窗口 A 和 B .
I have two browser windows A and B open side by side.
当某人单击窗口 A 中的按钮时,我想在窗口 B 中运行一个功能.
When someone clicks a button in window A I want to run a function in window B.
我当前在窗口 B 中使用hashchange事件,在窗口 A 中使用window.open(myurl,myurl)告诉另一个窗口开始运行功能,但是当网址更改时,效果不是很好.
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.
JavaScript是否有另一种解决方案来初始化当前窗口之外的事件?
Is there another solution in javascript to init events outside the current window?
我能想到的一种方法是,触发一个本地存储更改,其他选项卡/窗口将检测到该更改,只要它们都属于同一个域即可共享相同的localStorage. 如果在事件触发选项卡中您执行以下操作:
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');
然后您可以在另一个选项卡/窗口上检测到该更改并对它做出反应(我在这里使用的是JQuery,与纯Javascript类似):
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 ;)
}
});
在触发窗口中两次更改localStorage的原因是能够使用相同的代码再次触发该事件(在同一窗口或其他窗口中),因为您检测到localStorage变量从一个已知值变为另一个已知值.
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.