1

OnRequest.addListenersendRequestと関数を使用して、コンテンツスクリプトからバックグラウンドスクリプトに値を渡す方法を教えてくれる投稿がたくさんあることがわかりました。

ただし、ユーザー入力パラメーターをコンテンツスクリプトに渡したい。どうすればそれを達成できますか?

4

1 に答える 1

4

コンテンツスクリプトをどのように挿入するかに応じて、さまざまな方法でそれを行うことができます。まず、一致パターンを使用してマニフェストを介して注入していて、そのイベントのイベントに基づくデータが必要な場合は、次のcontent scriptようにします。

コンテンツスクリプト

chrome.extension.sendMessage({text:"getStuff"},function(reponse){
  //This is where the stuff you want from the background page will be
  if(reponse.stuff == "test")
    alert("Test received");
});

Background.js

chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
  if(message.text == "getStuff")
    sendResponse({stuff:"test"}); //This would be where you send your stuff
});

プログラムによる注入を行っていて、注入する時点のデータがある場合は、このようなものが機能します。挿入したいタブを取得する方法をすでに知っていると思います。

Background.js

//given tab is the tab ID you already have
chrome.tabs.executeScript(tab,{file:"contentScript.js"},function(){
  chrome.tabs.sendMessage(tab, {stuff:"test"});
});

contentScript.js

chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
  //This is where the stuff you want from the background page will be
  if(message.stuff == "test")
    alert("Test received");
});

ポップアップから既に挿入したコンテンツスクリプトにデータを送信する必要がある場合は、次のようにすることができます。

Popup.js

chrome.tabs.query({active:true,currentWindow:true}, function(tab) {
  chrome.tabs.sendMessage(tab[0].id, {stuff:"test"});
});

contentScript.js

chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
  //This is where the stuff you want from the background page will be
  if(message.stuff == "test")
    alert("Test received");
});

これは、目的のタブが選択されている限り、スクリプトをどのように挿入したかに関係なく機能します。

于 2013-03-24T17:26:13.567 に答える