executeScript 的不稳定行为:"Cannot access a chrome:// URL" on http://www.imdb.com/list

Erratic behavior of executeScript: "Cannot access a chrome:// URL" on http://www.imdb.com/list

我正在某些 http://www.imdb.com/list... 特定的 url 上执行内容脚本。 大多数时候它工作正常,但有时不是。然后我用 F5 重新加载页面,再次,它在大多数时间都运行良好。 在事件页面中,我监听 onDOMContentLoaded

chrome.webNavigation.onDOMContentLoaded.addListener(listener, {'url': urlFilter});

监听器挂的不错

function listener(tab){
    t=tab;
    chrome.tabs.executeScript(tab.id, {file: 'elementoWeb 2.1.js'}, function(resultado){
        if(chrome.runtime.lastError)
            console.log('Ejecutando elementoWeb.js, chrome.runtime.lasterror: ', chrome.runtime.lastError, '\nTab: ', t);
    }); 
    chrome.tabs.executeScript(tab.id, {file: 'imdbListaCs.js'}    , function(resultado){
        if(chrome.runtime.lastError)
            console.log('Ejecutando imdbListaCs.js, chrome.runtime.lasterror: ', chrome.runtime.lastError, '\nTab: ', t);
    });
}

当失败时,有两个这样的控制台日志,每次执行尝试一个:

Ejecutando elementoWeb.js, chrome.runtime.lasterror:  Object {message: "Cannot access a chrome:// URL"} 
Tab:  Object {frameId: 0, processId: 320, tabId: 405, timeStamp: 1421159075402.253, url: "http://www.imdb.com/list/......"}
frameId: 0
processId: 320
tabId: 405
timeStamp: 1421159075402.253
url: "http://www.imdb.com/list/......"
__proto__: Object

(我缩短了 imdb 的 urls)

标签 405 是带有 imdb.com 页面的标签。不是 chrome://url.

有时错误消息会有所不同:

Cannot access contents of url "chrome-devtools://devtools/bundled/devtools.html?&dockSide=undocked&toolbarColor=rgba(223,223,223,1)&textColor=rgba(0,0,0,1)". Extension manifest must request permission to access this host.

我没有激活任何开发工具的实验。

有人遇到同样奇怪的问题吗?

chrome.webNavigation.onDOMContentLoaded事件没有得到Tab object, but an object that contains information about the navigation. Take a look at the documentation of the event listener's callback function(或者看看你打印到控制台的对象!),它表明选项卡的ID在tabId 属性.

在您的代码中,您读取了一个不存在的 属性 参数(因此 undefined)并将其传递给 chrome.tabs.executeScript. Because the tab ID is missing, executeScript defaults to the active tab of the current window. When the navigation is triggered while you're at a different window or tab, the content script is inserted in the wrong tab. If you don't have access to that tab (e.g. because it's chrome://newtab), Chrome refuses to execute the script. If you're viewing a devtools window, then you'll get an error about that window (though not any more starting Chrome 41)。

要解决您的问题,请将函数更改为

function listener(details) { // changed "tab" to "details"
    chrome.tabs.executeScript(details.tabId, // (was "tab.id")