Call a JavaScript function across browser tabs

前端 未结 4 2011
离开以前
离开以前 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:01

    You should show your html in the first place, but i assume your tab has a link, you could do like this:

    <a href="some-path" id="tab2">Tab 2</a>
    

    JQuery:

    $('#tab2').click(function(){
       // your function code here
    
      // prevent default action
      return false;
    })
    
    0 讨论(0)
  • 2020-12-10 18:05

    I really cannot understand what you mean by the question.

    But you can pass javascript function references as arguments to other functions.(Be wary of object execution contexts).

    So while initializing "tab2", you could send in the function reference of execute of "tab1", to "tab2".

    Could have given a more definitive answer with an example , had you been clearer in your question.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-10 18:09

    JavaScript can not do cross-tab scripting in the browser (it is a security risk).

    If however the 2nd tab was opened from a window.open() call, and the browsers settings were set up such that new popup windows open in a new tab instead -- then yes, "tab1" can talk to "tab2"

    the first tab/window is called the opener and thus the new tab can call functions on the opener using this format:

    opener.doSomething();
    

    likewise, the opener can call functions on the new tab/popup, by using the variable it created when creating the popup window.

    var myPopup = window.open(url, name, features);
    myPopup.doStuffOnPopup();
    
    0 讨论(0)
提交回复
热议问题