47

私はその質問がさまざまな方法で繰り返し尋ねられていることを知っていますが、私はすべての回答を通過しようとしました(うまくいけば誰も見逃しませんでした)私のために働いた。ここでChromeの拡張機能:背景からコンテンツへのスクリプトのsendMessageが機能しない

私の拡張機能のコードです:

マニフェスト:

{ 
"name": "test", 
"version": "1.1", 
"background": 
{ 
    "scripts": ["contextMenus.js"] 
}, 

"permissions": ["tabs", "<all_urls>", "contextMenus"], 

"content_scripts" : [ 
    { 
     "matches" : [ "http://*/*" ], 
     "js": ["jquery-1.8.3.js", "jquery-ui.js"], 
     "css": [ "jquery-ui.css" ], 
     "js": ["openDialog.js"] 
    } 
], 

"manifest_version": 2 
} 

contextMenus.js

function onClickHandler(info, tab) { 
    if (info.menuItemId == "line1"){ 

     alert("You have selected: " + info.selectionText); 

     chrome.extension.sendMessage({action:'open_dialog_box'}, function(){}); 

     alert("Req sent?"); 

    } 
} 

chrome.contextMenus.onClicked.addListener(onClickHandler); 

chrome.runtime.onInstalled.addListener(function() { 

    chrome.contextMenus.create({"id": "line1", "type": "normal", "title": "I'm line 1",  "contexts":["selection"]}); 

}); 

openDialog.js

chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) { 

    if (msg.action == 'open_dialog_box') { 
    alert("Message recieved!"); 
    } 
}); 

バックグラウンドページの2つのアラートは、content_scriptの1つは実行されませんが、

コンソールログのメッセージ:ポートエラー:接続を確立できませんでした。受信終了は存在しません。

私の責任はどこですか?あなたの背景ページで

+0

'chrome.extension.sendMessage()'ではなく、コンテンツスクリプトにメッセージを送るには 'chrome.tabs.sendMessage()'を使うべきです。 – apsillers

答えて

89

あなたの代わりにあなたが現在そうであるようにchrome.extension.sendMessageを使用しての

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){ 
    chrome.tabs.sendMessage(tabs[0].id, {action: "open_dialog_box"}, function(response) {}); 
}); 

を呼び出す必要があります。

chrome.extension機能はメッセージをコンテンツスクリプトに送信しますが、他のすべての拡張機能にメッセージを送信します。

+4

ありがとうございます。それは 'chrome.tabs.sendMessage' [それを送るタブを指定しなければなりません](http://developer.chrome.com/extensions/messaging.html)以外は正しいです。したがって、解決策は次のように変更されます: 'chrome.tabs.query({active:true}、function(tabs){ \t \t chrome.tabs.sendMessage(tab.id、{action:" open_dialog_box "}、function(response) { \t \t \t}); \t \t}); – Subway

+1

もちろん、はい、もちろんです。私は私の答えを更新します。 – apsillers

+0

OK、質問に追加した編集を削除しました。 – Subway

関連する問題