2012-05-16 50 views
1

我一直在搜索所有SO,並通過谷歌文檔閱讀,但我似乎無法找到解決方案。內容腳本:未捕獲TypeError:無法讀取undefined屬性'onRequest'

我的Chrome擴展正在注入一個內容腳本,我想設置一個onRequest.listener以便將請求發送到內容腳本。這是我以前用於onRequest.listenerthe script。問題是我不斷收到這個錯誤,原因不明。

錯誤消息:

Uncaught TypeError: Cannot ready property 'onRequest' of undefined

contentscript.js line 1;

下面是相關的代碼...

manifest.json的

{ 
    "name": "Injector Extension", 
    "version": "1.0", 
    "manifest_version": 1, 
    "icons": { "128": "icon.png" }, 
    "browser_action": { 
    "default_icon": "icon.png", 
    "default_title": "Injector Extension", 
    "default_popup": "popup.html" 
    }, 
    "options_page": "options.html", 
    "background": { 
    "page": "background.html" 
    }, 
    "permissions": [ 
    "tabs", 
    "http://*/*", 
    "https://*/*", 
    "unlimitedStorage"], 
    "content_scripts": [{ 
     "matches": [" (injector specific url) "], 
     "js": ["contentscript.js"] 
    }], 
    "web_accessible_resources": ["js/script.js"] 
} 

內容腳本

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 
    if (request.method == "fromPopup") { 

    // Send JSON data back to Popup. 
    sendResponse({data: "from Content Script to Popup"}); 

    } else { 
    sendResponse({}); // snub them. 
    } 
}); 

彈出

chrome.tabs.getSelected(null, function(tab) { 
    chrome.tabs.sendRequest(tab.id, {method: "fromPopup", tabid: tab.id}, function(response) { 
     console.log(response.data); 
    }); 
}); 
+0

調試器的請不要張貼圖片,只需交錯誤消息以及錯誤發生時給定代碼的哪一行。 – Bergi

+0

已編輯的問題。 –

回答

5

chrome.extension.onRequest.addListener只能在擴展上下文。它不會在內容腳本中運行。

chrome.extension.sendRequest內容腳本上下文作品

相應更新,並將努力。

編輯:來鳳縣簡單的信息傳遞:

擴展腳本:

chrome.extension.onRequest.addListener(function(r,s,sr){ 
    if(r==='HELLO') return sr.call(this,'BACK AT YOU'); 
}); 

內容腳本:

chrome.extension.sendRequest('HELLO', function(data){ alert(data); }); 
// will alert "BACK AT YOU" 
+0

那麼將請求發送到我的內容腳本的最佳方式是什麼? –

+0

看看文檔;沒有複雜的消息傳遞,'sendRequest'接受一個'responseCallback'函數作爲第二個參數;這個回調有一個'response'參數,'onRequest'處理程序可以通過調用帶有參數的'sendResponse'(第三個參數)返回到內容腳本。我會更新一個例子,只要堅持。 –

+0

噢好吧,那沒什麼大不了的,我理解這個概念。我只是想知道我是否應該做'響應回調'或'長壽命連接'。我想你已經回答了我的問題。再次感謝! –

相關問題