我正在努力研究我认为相当基本的Chrome扩展。我有一个选项页面,用户可以在其中选择颜色,然后,从内容脚本,在每个其他页面上,左上角会有一个所选颜色的框。由于某种原因,内容脚本页面将使用默认值,但选项页面不起作用。你能告诉我为什么吗? 值得一提的是,对于选项页面,没有任何内容打印到日志中。
的manifest.json:
{
"name": "Iframe",
"description": "",
"version": "1",
"manifest_version": 2,
"options_page": "options.html",
"background": { "scripts": ["background.js"] },
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"anotherscript.js"
],
"all_frames": true
}
],
"permissions": [
"<all_urls>"
]
}
Options.html:
<html>
<head>
<title>Options for Color Chooser</title>
</head>
<body id="body">
<h1>Favorite Color</h1>
<select id="color">
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
<br />
<button id="save">Save</button>
<br />
<button id="default">Restore default</button>
<script type="text/javascript" src="options.js"></script>
</body>
</html>
Option.js:
var defaultColor = "blue";
document.getElementById('body').addEventListener(function loadOptions() {
var favColor = localStorage["favColor"];
// valid colors are red, blue, green and yellow
if (favColor == undefined || (favColor != "red" && favColor != "blue" && favColor != "green" && favColor != "yellow")) {
favColor = defaultColor;
}
var select = document.getElementById("color");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
if (child.value == favColor) {
child.selected = "true";
break;
}
}
});
document.getElementById('save').addEventListener(function saveOptions() {
var select = document.getElementById("color");
var color = select.children[select.selectedIndex].value;
localStorage["favColor"] = color;
consol.log("saved");
});
document.getElementById('default').addEventListener(function eraseOptions() {
localStorage.removeItem("favColor");
location.reload();
consol.log("reloaded");
});
Background.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});
Content_script.js:
color = "blue";
chrome.runtime.sendMessage({method: "getLocalStorage", key: "favColor"}, function(response) {
color = response.data;
consol.log(response.data);
});
a = document.createElement("div");
a.style.width = "50%";
a.style.height = "50%";
a.style.position = "absolute"
a.style.top = "0px"
a.style.left = "0px"
a.style.backgroundColor = color;
a.style.zIndex = 9999999;
a.style.opacity = 0.1;
document.body.appendChild(a);
答案 0 :(得分:2)
你有consol.log
没有“e”且没有错误?这不太可能。您的事件处理程序是否被调用?考虑一下你的代码:
document.getElementById('default').addEventListener(function () { ... });
这里的活动名称/类型是什么?我想“点击”?尝试:
document.getElementById('default').addEventListener('click', function () { ... });
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener