我演示扩展如下
文件&角色
一)的manifest.json(Documentation)
B)myscript.js(内容脚本见Documentation)
c)background.js(背景HTML文件中看到Documentation)
d)popup.html(浏览器操作弹出见Documentation)
E)popup.js(从背景页面的修改值的受体)
的manifest.json
注册到马的所有文件nifest(VIZ背景,弹出窗口,内容脚本)的权限
{
"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
});
background.js通信
使用
onMessage()和
onConnect()听众
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.js。HTML
样品浏览器操作HTML页面注册popup.js避免Inline Scripting
<!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);
});
希望这可以帮助,让我知道如果你需要更多的信息
我不知道你在期待什么,但基于'但它“去”我浏览网页,而不是HTML扩展,这意味着,而不是点击我的扩展按钮时弹出,它会显示为当页面加载时被编码到内容脚本中。“我假设你只有在点击扩展按钮后才会使用alert()?如果它是真的,那么你就错了,因为你已经在后台脚本中添加了监听器而不是浏览器动作,这是预期的行为,如果你能清楚地发布所有相关的代码和期望,那将是非常好的,所以我们可以帮助你。 – Sudarshan
感谢您的回复。基本上我想要做的只是将内容脚本中的值传递给后台脚本。然后将它分配给一个变量并处理它(在后台脚本中),然后在点击我的扩展图标时在弹出窗口中显示该值。 我之前发布的代码基本上都是我迄今为止所做的。 如何将其添加到浏览器操作?简单地说:你会怎么做我想做的事? 在此先感谢。 – user1869935