【发布时间】:2011-07-16 11:08:33
【问题描述】:
我正在编写一个 Chrome 扩展程序,它使用内容脚本来修改网站的某些部分。在我尝试将选项页面添加到我的扩展程序之前,内容脚本运行良好。
现在我正在使用 options.html 文件将用户首选项保存到本地存储,您可以在此处看到:
<html>
<head><title>Options</title></head>
<script type="text/javascript">
function save_options() {
var select = document.getElementById("width");
var width = select.children[select.selectedIndex].value;
localStorage["site_width"] = width;
}
function restore_options() {
var fwidth = localStorage["site_width"];
if (!fwidth) {
return;
}
var select = document.getElementById("width");
for (var i = 0; i < select.children.length; i++) {
var child = select.children[i];
if (child.value == fwidth) {
child.selected = "true";
break;
}
}
}
</script>
<body onload="restore_options()">
Width:
<select id="width">
<option value="100%">100%</option>
<option value="90%">90%</option>
<option value="80%">80%</option>
<option value="70%">70%</option>
</select>
<br>
<button onclick="save_options()">Save</button>
</body>
</html>
我还有一个 background.html 文件来处理内容脚本和本地存储之间的通信:
<html>
<script type="text/javascript">
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "siteWidth")
sendResponse({status: localStorage["site_width"]});
else
sendResponse({});
});
</script>
</html>
然后是如下所示的实际内容脚本:
var Width;
chrome.extension.sendRequest({method: "siteWidth"}, function(response) {
width = response.status;
});
这些代码实际上都不起作用。它对我来说看起来足够可靠,但我不是一个非常有经验的程序员,所以我可能错了。
谁能通俗地向我解释一下localstorage?
【问题讨论】:
标签: javascript google-chrome local-storage