我正在尝试让一个简单的 Google Chrome 扩展程序工作,其中消息/变量流经以下每个步骤......
我已经想出了如何将消息/变量发送到 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
的文档严重缺乏它很难破译。一个简单的、可重用的示例在学习过程中会非常有帮助,因为我确信这是一个常见问题。
最佳答案
好的,更改代码中的一些内容应该可以使其按您想要的方式工作。并非我将要进行的所有更改都是必需的,但这就是我可能会这样做的方式。
内容脚本
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);
});
关于google-chrome-extension - Chrome 扩展 - 从 DOM 到 Popup.js 消息传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16322830/