运行tabs.executeScript时未选中runtime.lastError:选项卡已关闭

时间:2017-01-01 19:21:08

标签: javascript google-chrome google-chrome-extension

我的Chrome扩展程序使用以下代码:

chrome.tabs.onUpdated.addListener(
  function(tabId, changeInfo, tab) {
    if (changeInfo.status === 'complete') {
      chrome.tabs.executeScript(null, {file: "js/content.js"});   
    }
  }
);

如果我在加载网页时关闭浏览器,则扩展程序会崩溃。我相信这是因为以下错误:

Unchecked runtime.lastError while running tabs.executeScript: The tab was closed.

有谁知道我怎么能避免这个错误?

1 个答案:

答案 0 :(得分:2)

chrome.tabs.executeScript添加回调。类似的东西:

chrome.tabs.onUpdated.addListener(
  function(tabId, changeInfo, tab) {
    if (changeInfo.status === 'complete') {
      chrome.tabs.executeScript(null, {file: "js/content.js"},
        function(result) {
          // Process |result| here (or maybe do nothing at all).
        }
      );   
    }
  }
);

您可以在官方Chrome API网站上找到有关此功能的文档: https://developer.chrome.com/extensions/tabs#method-executeScript