2013-05-01 83 views
10

我试图得到一个简单的谷歌Chrome扩展工作,其中一个消息/可变流过每个以下步骤Popup.js消息...Chrome扩展 - 从DOM路过

  1. DOM内容(从特定的HTML标签)
  2. Contentscript.js
  3. Background.js
  4. Popup.js
  5. Popup.html

我已经想通了如何从它发送邮件/可变 Background.js和在一个方向(Background.js -> Popup.jsBackground.js -> Contentscript.js),而是通过成功的所有三个(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" 
    } 
] 

} 

我有一种感觉,我知道跳闸了什么,但严重缺乏文档它很难破译。一个简单的,可重用的例子在学习过程中会非常有用,因为我确定这是一个常见问题。

回答

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

这正是我一直在寻找。非常感激! – 2013-05-01 20:13:28

+0

我试过了。弹出窗口不显示任何内容。我根据我的网站改变了'fromDOM'的值,尽管 – 2014-08-29 10:38:17

+0

@Venky用你的代码问你自己的问题,我将能够更好地帮助你。 – BeardFist 2014-08-30 02:34:11