2013-06-24 53 views
3

我在嘗試從彈出窗口向我的內容發送消息時出現此錯誤。我想要做的是從我的content.js中獲取當前選項卡的文檔並將其發送到彈出窗口。我該如何解決這個錯誤?Chrome擴展端口錯誤:無法建立連接。接收結束不存在

{ 
    "manifest_version": 2, 
    "name": "Chrome Snapshot", 
    "description": "Save images and screenshots of sites to Dropbox.", 
    "version": "1.0", 
    "permissions": [ 
    "<all_urls>", 
    "tabs" 
    ], 
    "browser_action": { 
    "default_icon": "icon.png", 
    "default_popup": "html/popup.html" 
    }, 
    "background": { 
    "scripts": [ 
     "vendor/dropbox.min.js", 
     "vendor/jquery-2.0.2.min.js" 
    ], 
    "persistant": false 
    }, 
    "content_scripts" : [{ 
    "all_frames": true, 
    "matches" : ["*://*/*"], 
    "js" : ["js/content.js"], 
    "run_at": "document_end" 
    }] 
} 

JS/popup.js

chrome.runtime.sendMessage({message: 'hi'}, function(response) { 
    console.log(response); 
}); 

JS/content.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { 
    console.log('message', message); 
    sendResponse({farewell: 'goodbye'}); 
}); 

編輯#1仍然得到同樣的錯誤Port error: Could not establish connection. Receiving end does not exist. miscellaneous_bindings:235 chromeHidden.Port.dispatchOnDisconnect

固定拼寫錯誤「持久'清單
個更新JS/popup.js

chrome.tabs.query({'active': true,'currentWindow':true}, function(tab){ 
    console.log('from tab', tab[0]); 
    chrome.tabs.sendMessage(tab[0].id, {message: 'hi'}, function(response){ 
     console.log(JSON.stringify(response)); 
    }); 
    }); 

回答

3

你需要使用chrome.tabs.sendMessage將消息發送到內容的腳本。從Chrome的開發者網站的chrome.runtime.sendMessage規格:

Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage.

如果這不是一個不錯的選擇,你可以有每個內容腳本打開一個端口,你的背景頁面(這可能將需要持久的)和然後讓彈出頁面向您的後臺頁面發送消息,後臺頁面將通過每個端口轉發消息到所有內容腳本,以告訴他們發送消息回彈出頁面。 (使用chrome.runtime.connect。)

另外,您在清單文件中拼錯了「持久性」。我不希望你在發現問題之前一定要深入半小時。

相關問題