我的Demo扩展如下
文件和角色
a) manifest.json (文档)
b) myscript.js(内容脚本见文档)
c) background.js(背景 HTML 文件参见文档)
d) popup.html(浏览器操作弹出窗口见文档)
e) popup.js(后台页面修改值的接收器)
清单.json
将所有文件注册到具有权限的清单(即背景、弹出窗口、内容脚本)
{
"name":"Communication Demo",
"description":"This demonstrates modes of communication",
"manifest_version":2,
"version":"1",
"permissions":["<all_urls>"],
"background":{
"scripts":["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["myscript.js"]
}
],
"browser_action":{
"default_icon":"screen.png",
"default_popup":"popup.html"
}
}
myscript.js
使用sendMessage() API与后台页面通信
var d = document.domain;
chrome.extension.sendMessage({
dom: d
});
背景.js
使用onMessage()和onConnect()监听器为 Content 和 popup.js 添加了事件监听器
var modifiedDom;
chrome.extension.onMessage.addListener(function (request) {
modifiedDom = request.dom + "Trivial Info Appending";
});
chrome.extension.onConnect.addListener(function (port) {
port.onMessage.addListener(function (message) {
if (message == "Request Modified Value") {
port.postMessage(modifiedDom);
}
});
});
popup.html
示例浏览器操作 HTML 页面注册 popup.js 以避免内联脚本
<!doctype html>
<html>
<head>
<script src="popup.js"></script>
</head>
<body></body>
</html>
popup.js
使用Port\Long Lived Connection与后台页面通信以获取结果
var port = chrome.extension.connect({
name: "Sample Communication"
});
port.postMessage("Request Modified Value");
port.onMessage.addListener(function (msg) {
console.log("Modified Value recieved is " + msg);
});
希望这会有所帮助,如果您需要更多信息,请告诉我