2012-08-04 42 views
7

當嘗試,我得到了下面的錯誤我的內容 - 與後臺腳本之間的通信:Chrome擴展程序:端口錯誤:無法建立連接。接收結束不存在。

Port error: Could not establish connection. Receiving end does not exist. 
Error in event handler for 'undefined': Cannot read property 'message' of undefined  
TypeError: Cannot read property 'message' of undefined 

background.js

function onRequest(request, sender, callbackFunction) { 
    console.log("Me (BS) became this Message:" + request.message); 
    sendResponse({message: request.message}) 
}; 
chrome.extension.onRequest.addListener(onRequest); 

streamcloud.js

function contactBackground(nachricht){ 
    chrome.extension.sendMessage({message: nachricht}, function(response) { 
     console.log("The Background Script got the following Message: " + response.message); 
    }); 
} 

和我的manifest.jso ñ

{ 
    "name": "InstantWatch - Dev", 
    "manifest_version": 2, 
    "version": "0.7", 
    "permissions": ["tabs", "http://*/", "https://*/"], 
    "background": { 
    "scripts": ["background.js"] 
    }, 
    "browser_action": { 
    "default_title": "InstantWatch", 
    "default_icon" : "icon.ico" 
    }, 
    "content_scripts": [ 
    { 
     "matches": ["http://*/*", "http://*/*"], 
     "js": ["jquery.js", "streamcloud.js"] 
    } 
    ] 
} 

我找到了解決方案添加BACKGROUND_PAGE:用空background.html「background.html」,但由於BACKGROUND_PAGE因爲manifest_version不支持:2,我不能使用。

+0

的另一種方式,它解決我的問題,正是這個同樣的錯誤: http://stackoverflow.com/a/13565529/390747 – WooCaSh 2012-11-26 13:11:58

回答

20

sendMessageonRequest不兼容

如果您需要支持的Chrome 19和早期,使用onRequestsendRequest

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { 
    // Warning: Chrome 19- [receiver] 
}); 
chrome.extension.sendRequest(message, optional_sendResponse); 

對於的Chrome 20 - 25,使用chrome.extension.onMessagechrome.extension.sendMessage

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { 
    // Chrome 20+ 
}); 
chrome.extension.sendMessage(message, optional_sendResponse); 

對於鉻26+,使用chrome.runtime.onMessagechrome.runtime.sendMessage


注意:從Chrome 26開始,儘管沒有文檔,但過時的方法仍然受支持。如果您有機會,請更新您的擴展程序以使用新方法,以確保您的擴展程序將來仍能正常工作。
請參閱this answer以獲取與Chrome 20+兼容的代碼。

+2

+1用於指出文檔中的錯誤.. !!! – Amila 2012-09-11 09:50:52

3

而不是

chrome.extension.onRequest.addListener(onRequest); 

使用

chrome.extension.onMessage.addListener(onRequest); 

由於您使用的sendMessage而不是sendRequest將。

消息解析已在新版Chrome中更新。 sendRequest和onRequest已被棄用。建議使用sendMessage和onMessage。

請參閱message parsing between Content Script and Background的文檔。

+1

這適用於Chrome的20-25。在Chrome 26中,API再次發生了變化。請參閱[Rob W對此問題的回答](http://stackoverflow.com/a/11811936/3345375)以及[peterthinking對類似問題的回答](http://stackoverflow.com/a/18131296/3345375) 。 – jkdev 2015-03-02 19:10:05

相關問題