如何使用jQuery/Javascript将事件从标签/窗口发送到另一个 [英] How to send an event from a tab/window to another with jQuery/Javascript

查看:103
本文介绍了如何使用jQuery/Javascript将事件从标签/窗口发送到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当另一个Soundcloud窗口或选项卡正在播放时,Soundcloud如何停止当前播放的声音?

How does soundcloud do to stop current playing sound when another soundcloud window or tab is playing ?

我正在寻找一种无需使用子窗口设计即可将事件从选项卡/窗口发送到另一个事件的方法.

I'm looking for a way to send an event from a tab/window to another one, without using Child Window design.

我尝试使用自定义Cookie事件,但它没有影响其他标签.

I tried to use custom Cookie event but it did not affect other tabs.

推荐答案

使用localStorage .

您知道localStorage会触发事件吗?更具体地说,无论何时在另一个浏览上下文中添加,修改或删除项目,它都会触发一个事件.实际上,这意味着只要您在任意给定的选项卡中触摸localStorage,所有其他选项卡都可以通过侦听window对象上的storage事件来了解它,就像这样:

Did you know that localStorage fires an event? More specifically, it fires an event whenever an item is added, modified, or removed in another browsing context. Effectively, this means that whenever you touch localStorage in any given tab, all other tabs can learn about it by listening for the storage event on the window object, like so:

window.addEventListener('storage', function(e){
  console.log(event.key, event.newValue);
});

每当一个选项卡修改了localStorage中的内容时,就会在其他所有选项卡中触发一个事件.这意味着我们只需在localStorage上设置值即可在浏览器选项卡之间进行通信.

Whenever a tab modifies something in localStorage, an event fires in every other tab. This means we're able to communicate across browser tabs simply by setting values on localStorage.

请参阅该文章作者的 local-storage 模块,该模块提供了可能对您有用:

See the local-storage module by the author of that article that offers an API that might be of some use to you:

ls.on(key, fn(value, old, url))
ls.off(key, fn)

这篇关于如何使用jQuery/Javascript将事件从标签/窗口发送到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆