Call a JavaScript function across browser tabs

前端 未结 4 2010
离开以前
离开以前 2020-12-10 17:37

I have two browser tabs, tab1 and tab2.

I have a function called execute in tab1, which I would like to call from the page in tab2.

Is that possible and if s

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 18:08

    There's a tiny open-source component to sync/lock/call code in multiple tabs that allows you send messages between tabs (DISCLAIMER: I'm one of the contributors!)

    https://github.com/jitbit/TabUtils

    That can be called like this:

    TabUtils.BroadcastMessageToAllTabs("messageName", data);
    

    And then in another tab:

    TabUtils.OnBroadcastMessage("messageName", function (data) {
        //do something
    });
    

    It is based on the onstorage event, you can simply modify the code for you need, it's very simple.

提交回复
热议问题