2013-05-01 5 views
10

パッシングPopup.jsメッセージへのDOM ...クローム拡張 - 私はメッセージ/変数は、以下の各ステップを流れ作業シンプルなGoogle Chrome拡張機能を取得しようとしている

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

私は1つの方向(Background.js -> Popup.jsまたはBackground.js -> Contentscript.js)でそれからのメッセージ/変数にBackground.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> 

manifest.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その解読が難しい。シンプルで再利用可能な例は、これが共通の問題であると確信しているので、学習プロセスで非常に役立ちます。

答えて

16

あなたのコードでいくつか変更することで、好きなように動作させることができます。私がしようとしている変更のすべてが必要なわけではありませんが、これが私のやり方です。

コンテンツスクリプト

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); 
}); 
+0

これはまさに私が探していたものです。とても有難い! –

+0

私はこれを試しました。ポップアップには何も表示されません。 –

+0

@Venkyはあなたのコードであなた自身の質問をしますが、私はあなたをより良く助けることができます。 – BeardFist

関連する問題