0

クロム拡張でメッセージを受け渡そうとしています。私は、この例(see here)に従う - :クロム拡張メッセージを渡す応答がありません:未定義

content_script:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) { 
console.log(response.farewell); 
}); 

背景:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { 
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) { 
    console.log(response.farewell); 
}); 
}); 

popup.js

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) { 
    console.log(sender.tab ? 
     "from a content script:" + sender.tab.url : 
     "from the extension"); 
    if (request.greeting == "hello") 
     console.log("message recive") 
     sendResponse({farewell: "goodbye"}); 
}); 

私はコピー&ペーストをしましたが、 - メッセージを送信されません。エラーがポップアップ表示さ:

エラーイベントハンドラで(不明)のために:TypeError例外:未定義

間違いです

のプロパティを読み取ることができません「お別れ」?

答えて

0

閉じる中にポップアップが存在しません。

このように、メッセージが送信された時点では、リッスンする可能性はほとんどないため、undefinedとコールバック(およびchrome.runtime.lastErrorが設定されている)がコールされました。

アーキテクチャの観点からは、バックグラウンドページはメッセージを処理するために常に利用できるページです。そのように、onMessageリスナーは、にあります。ほとんどの場合、(すべてではありません)のケースがより良いです。

私は、この質問をもう一度見てみることをお勧めします。ここではいくつかの概念をより詳しく説明します:Pass a variable from content script to popup

また、このグリーティンググッドバイのサンプルコードはすべて単なる例に過ぎません。 JSON-serializableを渡すことができます。

+0

ありがとう、私は読むつもりです – blueberry

関連する問題