Chrome拡張機能でコンテンツスクリプトからpopup.htmlにデータを送信する方法 質問する

Chrome拡張機能でコンテンツスクリプトからpopup.htmlにデータを送信する方法 質問する

これは多数の投稿で質問されていることは承知していますが、正直わかりません。JavaScript、Chrome 拡張機能、その他すべてに不慣れで、このクラスの課題があります。そのため、クロス ドメイン リクエストを使用して、任意のページの DOM オブジェクトをカウントするプラグインを作成する必要があります。これまでは、Chrome 拡張機能 API を使用してこれを実現できました。問題は、contentScript.js ファイルから popup.html ページにデータを表示する必要があることです。その方法がわかりません。ドキュメントを読んでみましたが、Chrome でのメッセージングでは何をすればよいのか理解できません。

以下はこれまでのコードです。

マニフェスト

{
"manifest_version":2,

"name":"Dom Reader",
"description":"Counts Dom Objects",
"version":"1.0",

"page_action": {
    "default_icon":"icon.png",
    "default_title":"Dom Reader",
    "default_popup":"popup.html"
},

"background":{
    "scripts":["eventPage.js"],
    "persistent":false
},

"content_scripts":[
    {
        "matches":["http://pluralsight.com/training/Courses/*", "http://pluralsight.com/training/Authors/Details/*",                                          "https://www.youtube.com/user/*", "https://sites.google.com/site/*", "http://127.0.0.1:3667/popup.html"],
        "js":["domReader_cs.js","jquery-1.10.2.js"]
        //"css":["pluralsight_cs.css"]
    }
],

"permissions":[
    "tabs",
    "http://pluralsight.com/*",
    "http://youtube.com/*",
    "https://sites.google.com/*",
    "http://127.0.0.1:3667/*"
]

ポップアップ.html

<!doctype html>
<html>

    <title> Dom Reader </title>    
    <script src="jquery-1.10.2.js" type="text/javascript"></script>
    <script src="popup.js" type="text/javascript"></script>

<body>
    <H1> Dom Reader </H1>
    <input type="submit" id="readDom" value="Read DOM Objects" />

   <div id="domInfo">

    </div>
</body>
</html>

イベントページ.js

var value1,value2,value3;

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action == "show") {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.pageAction.show(tabs[0].id);
    });
}

value1 = request.tElements;
});

ポップアップ

$(function (){
$('#readDom').click(function(){
chrome.tabs.query({active: true, currentWindow: true}, function (tabs){
    chrome.tabs.sendMessage(tabs[0].id, {action: "readDom"});

 });
});
});

コンテンツスクリプト

var totalElements;
var inputFields;
var buttonElement;

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse){
if(request.action == "readDom"){

    totalElements = $("*").length;
    inputFields = $("input").length;
    buttonElement = $("button").length;


}
})

chrome.runtime.sendMessage({ 
action: "show", 
tElements: totalElements, 
Ifields: inputFields, 
bElements: buttonElement 

});

どのような助けでも大歓迎です。また、私がやったような初心者的なことは避けてください :)

ベストアンサー1

あなたは間違いなく正しい方向に進んでいますが(実際、終わりにかなり近づいています)、あなたのコードにはいくつかの(私見ですが)悪い習慣があります(たとえば、このような些細なタスクのためにライブラリ全体(jquery)を挿入する、不要な権限を宣言する、API メソッドへの余分な呼び出しを行うなど)。
私はあなたのコードを自分でテストしていませんが、ざっと見たところ、次の点を修正すると、(最適には非常に近いとは言えませんが)機能するソリューションになると思います。

  1. マニフェスト: コンテンツスクリプトの順序を変更し、jqueryを先頭にします。関連文書:

「js」 [...] 一致するページに挿入されるJavaScriptファイルのリスト。これらは挿入されます表示される順番にこの配列内。

(強調は筆者による)

  1. コンテンツスクリプト: 移動chrome.runtime.sendMessage({...})ブロック内部リスナーonMessageコールバック。

とはいえ、私が提案するアプローチは次のとおりです。

制御フロー:

  1. コンテンツ スクリプトは、いくつかの条件に一致する各ページに挿入されます。
  2. コンテンツ スクリプトが挿入されると、イベント ページ (非永続的なバックグラウンド ページとも呼ばれます) にメッセージが送信され、イベント ページはタブにページ アクションを添付します。
  3. ページアクションポップアップが読み込まれるとすぐに、コンテンツスクリプトにメッセージが送信され、必要な情報が要求されます。
  4. コンテンツ スクリプトはリクエストを処理し、応答してページ アクション ポップアップに情報を表示できるようにします。

ディレクトリ構造:

          root-directory/
           |__img
               |__icon19.png
               |__icon38.png
           |__manifest.json
           |__background.js
           |__content.js
           |__popup.js
           |__popup.html

マニフェスト.json:

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",
  "offline_enabled": true,

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },

  "content_scripts": [{
    "matches": ["*://*.stackoverflow.com/*"],
    "js": ["content.js"],
    "run_at": "document_idle",
    "all_frames": false
  }],

  "page_action": {
    "default_title": "Test Extension",
    //"default_icon": {
    //  "19": "img/icon19.png",
    //  "38": "img/icon38.png"
    //},
    "default_popup": "popup.html"
  }

  // No special permissions required...
  //"permissions": []
}

背景.js:

chrome.runtime.onMessage.addListener((msg, sender) => {
  // First, validate the message's structure.
  if ((msg.from === 'content') && (msg.subject === 'showPageAction')) {
    // Enable the page-action for the requesting tab.
    chrome.pageAction.show(sender.tab.id);
  }
});

コンテンツ.js:

// Inform the background page that 
// this tab should have a page-action.
chrome.runtime.sendMessage({
  from: 'content',
  subject: 'showPageAction',
});

// Listen for messages from the popup.
chrome.runtime.onMessage.addListener((msg, sender, response) => {
  // First, validate the message's structure.
  if ((msg.from === 'popup') && (msg.subject === 'DOMInfo')) {
    // Collect the necessary data. 
    // (For your specific requirements `document.querySelectorAll(...)`
    //  should be equivalent to jquery's `$(...)`.)
    var domInfo = {
      total: document.querySelectorAll('*').length,
      inputs: document.querySelectorAll('input').length,
      buttons: document.querySelectorAll('button').length,
    };

    // Directly respond to the sender (popup), 
    // through the specified callback.
    response(domInfo);
  }
});

ポップアップ:

// Update the relevant fields with the new data.
const setDOMInfo = info => {
  document.getElementById('total').textContent = info.total;
  document.getElementById('inputs').textContent = info.inputs;
  document.getElementById('buttons').textContent = info.buttons;
};

// Once the DOM is ready...
window.addEventListener('DOMContentLoaded', () => {
  // ...query for the active tab...
  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, tabs => {
    // ...and send a request for the DOM info...
    chrome.tabs.sendMessage(
        tabs[0].id,
        {from: 'popup', subject: 'DOMInfo'},
        // ...also specifying a callback to be called 
        //    from the receiving end (content script).
        setDOMInfo);
  });
});

ポップアップ.html:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="popup.js"></script>
  </head>
  <body>
    <h3 style="font-weight:bold; text-align:center;">DOM Info</h3>
    <table border="1" cellpadding="3" style="border-collapse:collapse;">
      <tr>
        <td nowrap>Total number of elements:</td>
        <td align="right"><span id="total">N/A</span></td>
      </tr>
      <tr>
        <td nowrap>Number of input elements:</td>
        <td align="right"><span id="inputs">N/A</span></td>
      </tr>
      <tr>
        <td nowrap>Number of button elements:</td>
        <td align="right"><span id="buttons">N/A</span></td>
      </tr>
    </table>
  </body>
</html>

おすすめ記事