我想将消息从网页传递到内容脚本到背景页面。做了以下不起作用的代码。 当我点击clickme按钮 - >发送消息到chrome扩展
的manifest.json
{
"name": "Fixes",
"version": "2",
"manifest_version": 2,
"description": "SomeFixes",
"permissions": ["tabs", "http://*/*", "https://*/*", "storage"],
"options_page": "options.html",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["http://*/*","https://*/*"],
"js": ["contentscript.js"],
"run_at": "document_start"
}],
"background":{
"scripts":["background.js"]
}
}
page.html中。
<html>
<head></head>
<body>
<script>
var go = function() {
var event = document.createEvent('Event');
event.initEvent('hello');
document.dispatchEvent(event);
}
</script>
<a href="javascript:go();">Click me</a>
</body>
</html><html>
<head></head>
<body>
<script>
var go = function() {
var event = document.createEvent('Event');
event.initEvent('hello');
document.dispatchEvent(event);
}
</script>
<a href="javascript:go();">Click me</a>
</body>
</html>
contentscript.js
document.addEventListener("hello", function(data) {
chrome.runtime.sendMessage("test");
})
background.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
alert("message received");
});
理念基本上是从网页接收数据到扩展名。