Is it possible to determine a tab's opener within a Google Chrome extension?

后端 未结 4 1962
遥遥无期
遥遥无期 2020-12-31 17:37

I am looking for a way to determine a given tab\'s opener (parent tab) within a Google Chrome extension.

I\'ve looked at the documention for Tab but there doesn\'t r

相关标签:
4条回答
  • 2020-12-31 18:28

    Further investigation has revealed that onCreatedNavigationTarget() does not always fire when you think it would to indicate an opener-opened relationship.

    An additional hint can sometimes be found in the Tab object returned by chrome.tabs.onCreated/onUpdated in the .openerTabId parameter.

    A comprehensive solution will probably have to rely on multiple of the methods described in these answers.

    0 讨论(0)
  • 2020-12-31 18:35

    Chrome has added an experimental extension API which can accomplish this -- specifically webNavigation.onBeforeRetarget. http://code.google.com/chrome/extensions/experimental.webNavigation.html

    However since this is still experimental (not usable in Chrome stable versions or releasable on the Chrome Web Store) I have ended up using another approach.

    Basically:

    In content_script.js:

    chrome.extension.sendRequest({
        request: {
            op: "pageLoadStarted", 
            url: document.location.href, 
            referrer: document.referrer
        }
    }); 
    

    In background.html:

    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 
        console.log('onRequest: ' + JSON.stringify(request)); 
        console.log(JSON.stringify(sender)); 
      }); 
    

    This approach allows me to obtain the referrer of a tab, which I can then correlate with an existing tab's url. This isn't always a one-to-one mapping, so I do some additional magic such as preferring the currently selected tab as the opener if its url matches the new tab's referrer.

    This really is just a hack to approximate the functionality that would be provided more simply and accurately by webNavigation.onBeforeRetarget or window.opener.

    0 讨论(0)
  • 2020-12-31 18:39

    Update: it is now possible to reliably determine a tab's opener tab within a Chrome extension natively using the newly added webNavigation API, and specifically by hooking the onCreatedNavigationTarget event.

    https://code.google.com/chrome/extensions/trunk/webNavigation.html

    0 讨论(0)
  • 2020-12-31 18:43
    port.onMessage.addListener(
         function(msg) {
             var tabid = port.sender.tab.openerTabId;
             console.log("Received message from tab that was opened by tab id : " + tabid);
             // reliably shows the tab id of the tab that opened
             // the tab sending the message
         }); 
    
    0 讨论(0)
提交回复
热议问题