How to send an event from a tab/window to another with jQuery/Javascript

纵饮孤独 提交于 2019-12-12 20:10:23

问题


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.

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


回答1:


Use localStorage.

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);
});

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.

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)



回答2:


Not sure if you are looking for this? Server Sent Events.

http://www.w3schools.com/htmL/html5_serversentevents.asp

<script>
    var source = new EventSource("demo_sse.php");
    source.onmessage = function(event) {
        document.getElementById("result").innerHTML += event.data + "<br>";
    };
</script>

For anyone else interested in the old-school, access of a window via child/parent, there is this example. In your parent page, launch a child page, and keep the myWindow reference around. This allows you access to the entire DOM of the child window. You can then control child => parent or parent => depending on how you want to control things.

<script>
    var myWindow = window.open("", "MsgWindow", "width=200, height=100");
    // Or if you already have a webpage:
    // var myWindow = window.open("MyWebpage.html", "MsgWindow", "width=200, height=100");

    myWindow.document.write("<script>var test = 10;</s"+ "cript>");
    myWindow.document.write("<p>This window's name is: " + myWindow.name + "</p>");

    alert(myWindow.test); // displays 10, stored in the other window.

    myWindow.close("MsgWindow");
</script>


来源:https://stackoverflow.com/questions/27933682/how-to-send-an-event-from-a-tab-window-to-another-with-jquery-javascript

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