How to send an event from a tab/window to another

2019-07-19 18:33发布

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.

2条回答
\"骚年 ilove
2楼-- · 2019-07-19 18:48

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)
查看更多
干净又极端
3楼-- · 2019-07-19 18:56

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>
查看更多
登录 后发表回答