2013-06-28 28 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並不知道你想要在那個窗口中插入內容腳本。 –