【发布时间】:2013-05-01 17:05:23
【问题描述】:
我正在尝试让一个简单的 Google Chrome 扩展程序工作,其中消息/变量流经以下每个步骤...
- DOM 内容(来自特定的 HTML 标记)
- Contentscript.js
- Background.js
- Popup.js
- Popup.html
我已经想出了如何将消息/变量发送到 Background.js 并从它在一个方向(Background.js -> Popup.js 或Background.js -> Contentscript.js),但是无法成功通过所有三个 (Contentscript.js -> Background.js -> Popup.js)。这是我演示中的文件。
Dom
<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 来说,文档严重缺乏,很难破译。一个简单、可重复使用的示例对学习过程非常有帮助,因为我确信这是一个常见问题。
【问题讨论】:
标签: google-chrome-extension sendmessage