2013-06-28 23 views
0

这个想法很简单。打开一个窗口,然后在该新窗口上调用chrome.tabs.executeScript。Chrome扩展程序不会一直执行

不幸的是,除了打开一个新窗口,它什么都不做。

function openc(url) { 
    window.open(url); 
    chrome.tabs.executeScript(null, {file: "removeContent.js"}); 
    console.log("hi"); 
} 

document.addEventListener('DOMContentLoaded', function() { 
    openc("http://www.asdf.com/"); 
}); 

回答

0

首先,请确保您有host permissions在页面上进行操作。

如果你总是要运行的特定网页上的脚本,就足够了仅使用内容的脚本,通过registration via the manifest file:如果要动态执行内容脚本新页面

"content_scripts": [ 
    { 
     "matches": ["http://example.com/*"], 
     "js": ["open-asdf.js"] 
    }, 
    { 
     "matches": ["http://www.asdf.com/*"], 
     "js": ["removeContent.js"] 
    } 
    ], 

,你应该使用chrome.tabs.create方法打开新标签,并在回调中插入脚本。这些方法只能在扩展的过程中使用,因此请确保代码在background/event/popup/options/..页面上运行。

chrome.tabs.create({ 
    url: 'http://www.asdf.com/' 
}, function(tab) { 
    chrome.tabs.executeScript(tab.id, {file: "removeContent.js"}, function() { 
     if (chrome.runtime.lastError) { 
      console.error(chrome.runtime.lastError.message); 
     } 
    }); 
}); 
+0

chrome.tabs.create精美地工作。只是几个问题:什么是“功能(选项卡)”中的“选项卡”?为什么当我尝试使用window.open(url)时它不工作? – nlsun

+0

@ user2152914点击我答案中的蓝色链接,它会将您带到文档中,该文档解释了选项卡的含义。 'tab'提供你刚刚创建的标签信息,其标识符被传递给'chrome.tabs.executeScript'。 'window.open'不提供这个标识符,所以Chrome并不知道你想要在那个窗口中插入内容脚本。 –