background.html >> contentscript.js(Chrome拡張子)を通過するメッセージに巻き込まれます

StackOverflow https://stackoverflow.com/questions/8858730

質問

私はそれが何千回もここにあったことを知っていますが、私は今立ち往生しています。私はたくさんの答えを読み、code.google.comを勉強しましたが、成功しませんでした。 Chrome拡張機能でリクエストを送信しようとしています background.htmlcontentscript.js. 。しかし、私はなんとかそれを反対に機能させることができました。

内部のコード background.html:

  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
      console.log(response.farewell);
     });
  });

内部のコード contentscript.js:

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
    else
      sendResponse({farewell: "nope"});
});

manifest.json コミュニケーションが逆方向に機能しており、他のものが適切に機能するため、問題ないはずです。ありがとうございました!

役に立ちましたか?

解決

あなたのコードは良いです、あなたのトリガーに何か問題があるに違いありません。コードを使用して簡単な拡張機能を作成しましたが、機能しました。これらの2つのビットを背景とContentscriptに追加します。次に、任意のページでRMBを選択し、「メッセージの送信」を選択します。アラートを受け取る必要があります。

background.html

var menuid = chrome.contextMenus.create({"title":"Send Message", "onclick": SendMessage, "documentUrlPatterns":["http://*/*"]});

function SendMessage() {        
    chrome.tabs.getSelected(null, function(tab) {
            chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function(response) {
                console.log(response.farewell);
             });
    });
}

contentscript

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello") {
            alert('hello');
      sendResponse({farewell: "goodbye"});
        }
    else
        {
            alert('goodbye');
      sendResponse({farewell: "nope"});
        }
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top