2013-01-02 81 views
0

我想從我的背景腳本訪問功能的內容腳本以那種方式 -chrome.extension.getViews()返回麻煩

content.js

window.DOsomething = function(){ 
    console.log('Works?'); 
} 

背景。 JS

var popups = chrome.extension.getViews(); 
if (popups.length != 0) { 
      var popup = popups[0]; 
      popup.DOsomething(); 
} 

但它不工作!它會拋出一個錯誤Uncaught TypeError: Object [object Window] has no method 'DOsomething',但是當我在我的內容腳本中執行console.log(window)時 - 它顯示我存在此類方法(DOsomething)!但在popups[0]列表中沒有這樣的方法,我真的不明白這樣的結果

回答

2

這是Chrome擴展名爲isolated world的已知功能。內容腳本被注入目標頁面,不能直接從擴展的其他部分訪問。要與你進行互動,你應該使用messaging

這裏有點過時SO answer to a related question這可能有助於做出全貌。在答案中,您應該修改代碼以使用sendMessage而不是sendRequest,該代碼因第一個而被刪除。

例如,你在後臺頁面放置以下調用(從資料爲準):

chrome.tabs.getSelected(null, function(tab) { 
    chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, // you can send "DoSomething" for example 
    function(response) { 
    console.log(response.farewell); 
    }); 
}); 

在內容腳本,你應該聽消息:

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) { 
    console.log(sender.tab ? 
       "from a content script:" + sender.tab.url : 
       "from the extension"); 
    if(request.greeting == "hello") 
     sendResponse({farewell: "goodbye"}); 
    // else if(request.greeting == "DoSomething") DoSomething(); 
}); 

我不't認爲getViews方法是你想要的,因爲它返回你的擴展頁面(背景,彈出窗口,選項),而不是你的內容腳本注入的頁面。我想你應該從你的內容腳本到後臺頁面的sendMessages,以便後面的人「知道」所有的腳本主機頁面,或者你可以使用executeScript

chrome.tabs.executeScript(tabId, {code: 'DOsomething();'}) 
+0

感謝您的回答,但我怎麼能從背景sto內容腳本傳輸一些數據?我想嘗試,但沒有結果:( –

+0

@ lesha_89看看更新後的答案 – Stan

+0

tnx,我嘗試過但出現錯誤 - 「端口錯誤:無法建立連接,接收端不存在」和「錯誤未定義的處理程序:無法讀取未定義的屬性'告別'TypeError:無法讀取未定義的屬性'告別':( –

-1

background.js

var message = "What ever you want..."; 
var viewTabUrl = chrome.extension.getURL('main.html'); 
var views = chrome.extension.getViews(); 
for (var i = 0; view = views[i]; i++) 
{ 
    if (view.location.href == viewTabUrl) 
    { 
     view.DOsomething (messages); 
     break; 
    } 
} 

content.js

function DOsomething (message) 
{ 
// CODE 
} 
在上面的例子中

我曾經認爲 'main.html中' 是您的彈出(HTML)和包含content.js。