【问题标题】:How to get the tab in which a script has injected?如何获取脚本注入的选项卡?
【发布时间】:2016-09-03 02:19:29
【问题描述】:

在我的 Google Chrome 扩展页面中,我有一个内容脚本,它在匹配特定 URL 时注入脚本。

我正在尝试获取有关它所注入的选项卡的一些信息,以便在选项卡关闭时进行一些清理。

为此,我尝试从注入的脚本中调用chrome.tabs.getCurrent()。但是,它返回undefined,这很奇怪,因为在API 中它说getCurrent() 的返回

如果从非选项卡上下文中调用,则可能未定义(例如:a 背景页面或弹出视图)。

我从标签中调用它...

我哪里错了?

【问题讨论】:

  • content script that injects a script - 这意味着<script> 元素,对吗?这意味着它不再是一个内容脚本,而只是一个无法访问 chrome.* API 的页面脚本。请参阅Dynamic values in the injected code 部分。
  • 它可以访问chrome.runtime API - 我在注入的脚本中使用它。另外,如果它无法访问chrome.tabs,我不会看到错误吗?
  • 仅限chrome.runtime.sendMessage,并且仅当站点网址在"externally_connectable" 中列入白名单时才有效。
  • @wOxxOm 好的,没错。也许我没有以正确的方式这样做。我想要做的就是在我的注入脚本的选项卡关闭时执行一些清理。有什么建议吗?
  • 一个明显的方法是在后台脚本中使用chrome.tabs.onRemoved

标签: google-chrome google-chrome-extension


【解决方案1】:

在您的实际内容脚本中,要求后台页面提供标签 ID。

  • content.js

    var tabId; // global but not visible to the webpage as it's in an "isolated world"
    
    chrome.runtime.sendMessage('get-tabId', function(response) {
        tabId = response;
    
        // inject a page script and pass the tabId
        document.head.appendChild(document.createElement('script')).text = '(' +
            function(tabId) {
                tabId = tabId |0; // coerce to number
                console.log('Injected code got tabId: ', tabId);
            } + ')(' + tabId + ')';
    
    });
    
  • background.js

    chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
        if (msg === 'get-tabId') {
            sendResponse(sender.tab.id);
        }
    });
    

【讨论】:

    猜你喜欢
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多