11

メッセージ/変数が次の各ステップを通過する場所で、単純な Google Chrome 拡張機能を動作させようとしています...

  1. DOM コンテンツ (特定の HTML タグから)
  2. Contentscript.js
  3. Background.js
  4. Popup.js
  5. Popup.html

メッセージ/変数をBackground.jsに送信し、そこから一方向 (Background.js -> Popup.jsまたは)に送信する方法を理解しましたがBackground.js -> Contentscript.js、3 つすべてを正常に通過させることはできません ( Contentscript.js -> Background.js -> Popup.js)。これが私のデモのファイルです。

ドム

<h1 class="name">Joe Blow</h1>

Content.js

fromDOM = $('h1.name').text();

chrome.runtime.sendMessage({contentscript: "from: contentscript.js", title: fromDOM}, function(b) {
    console.log('on: contentscript.js === ' + b.background);
});

Background.js

chrome.tabs.getSelected(null, function(tab) {
    chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {

        sendResponse({background: "from: background.js"});
        console.log('on: background.js === ' + msg.title);

    });
});

Popup.js

chrome.extension.sendMessage({pop: "from: popup.js"}, function(b){
    console.log('on: popup.js === ' + b.background);

    $('.output').text(b.background);
});

Popup.html

<html>
<head>
  <script src="jquery.js"></script>
  <script src="popup.js"></script>
</head>
<body>

<p class="output"></p>

</body>
</html>

マニフェスト.json

{   
"name": "Hello World",   
"version": "1.0",
"manifest_version": 2,
"description": "My first Chrome extension.",
"background" : {
    "scripts": ["background.js"]
},
"permissions": [
    "tabs"
],
"browser_action": {     
    "default_icon": "icon.png",
    "default_popup": "popup.html"   
},
"content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["jquery.js","contentscript.js"],
      "run_at": "document_end"
    }
]

}

トリップアップが何であるかはわかっている気がしますが、manifest_version: 2解読が難しいため、ドキュメントが大幅に不足しています。これは一般的な問題であると確信しているため、単純で再利用可能な例は、学習プロセスに非常に役立ちます。

4

1 に答える 1

22

よし、コードのいくつかを変更するだけで、思いどおりに動作するはずです。これから行うすべての変更が必要なわけではありませんが、これは私が行う方法です。

コンテンツ スクリプト

var fromDOM = $('h1.name').text();
chrome.runtime.sendMessage({method:'setTitle',title:fromDOM});

バックグラウンド

var title;
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  if(message.method == 'setTitle')
    title = message.title;
  else if(message.method == 'getTitle')
    sendResponse(title);
});

Popup.js

chrome.runtime.sendMessage({method:'getTitle'}, function(response){
  $('.output').text(response);
});
于 2013-05-01T19:56:03.887 に答える