Javascript chrome.tabs.executeScript运行多次

Javascript chrome.tabs.executeScript运行多次,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,嘿,我有一个Chrome扩展,我需要停止加载给定的页面(在它开始之前) 因此,background.js中有以下代码: chrome.webNavigation.onBeforeNavigate.addListener(function (e){ // Important! there's more code that make sure this runs once - it isn't recuresive killPage(e.tab); }); function kil

嘿,我有一个Chrome扩展,我需要停止加载给定的页面(在它开始之前)

因此,background.js中有以下代码:

chrome.webNavigation.onBeforeNavigate.addListener(function (e){
    // Important! there's more code that make sure this runs once - it isn't recuresive
    killPage(e.tab);
});

function killPage(tabId){
    chrome.tabs.executeScript(tabId, {
        code: "window.stop();",
        runAt: "document_start"
    });
}
当我们使用window.stop时,执行脚本发生两次,当我们使用
document.open();document.close()
它无休止地运行,并达到最大调用堆栈

我们确保再次运行的唯一内容是执行脚本中的代码(而不是事件行
chrome.tabs.executeScript


如何使执行脚本只运行一次?

这是一个已经在Chrome 41-中修复的错误

它只发生在
document\u start
处,因此如果使用
document\u end
document\u idle
,则不会触发该错误(但稍后将激活该脚本)

它只发生在同步(阻塞)代码中。如果您可以使用异步API,那么您就可以在不碰到bug的情况下实现所需的效果。例如:

chrome.tabs.executeScript(tabId{
//使用setTimeout解决crbug.com/431263
代码:“setTimeout(函数(){window.stop();},0);”,
runAt:“文档开始”
});

看起来你删掉了对你的问题至关重要的代码。另外,请更好地解释你想做什么,这看起来像一个问题。@Xan这个问题在我看来很完整,根据你的说法,缺少了什么部分?@RobW好吧,如果问题是代码被多次运行,那么“更多的代码确保它运行一次”就会被删掉,这对我来说是个问题。很好,不用它你也能诊断出来。