【发布时间】:2012-04-10 03:03:55
【问题描述】:
我正在开发一个 chrome 扩展,我能够成功地将信息存储到本地存储中,但我的问题实际上是在本地存储中访问该信息。我没有返回任何东西,只是说 NULL。
我有两个文件:options.html 和 content.js。 options.html 是用户输入信息以保存到本地存储的地方,而 content.js 将访问要使用的信息。
options.html
$(function() {
// Insert new buttons (you'd probably not ACTUALLY use buttons, instead saving on blurs or every x seconds)
$("#save_buttons").after("<input type='submit' value='Save Form' id='saveData'>").after("<input type='submit' value='Clear Saved Data' id='clearData'>");
$("#saveData").click(function(e) {
// Don't actually submit form
e.preventDefault();
// Bit of generic data to test if saved data exists on page load
localStorage.setItem("flag", "set");
// serializeArray is awesome and powerful
var data = $("#hanes").serializeArray();
// iterate over results
$.each(data, function(i, obj) {
// HTML5 magic!!
localStorage.setItem(obj.name, obj.value);
});
});
// Test if there is already saved data
if (localStorage.getItem("flag") == "set") {
// Tell the user
$("header").before("<p id='message'>This form has saved data!</p>");
// Same iteration stuff as before
var data = $("#hanes").serializeArray();
// Only the only way we can select is by the name attribute, but jQuery is down with that.
$.each(data, function(i, obj) {
$("[name='" + obj.name +"']").val(localStorage.getItem(obj.name));
});
}
// Provide mechanism to remove data. You'd probably actually remove it not just kill the flag
$("#clearData").click(function(e) {
e.preventDefault();
localStorage.setItem("flag", "");
});
});
<form id="hanes" name="hanes">
First name: <input type="text" name="firstname" id="firstname" /><br />
Last name: <input type="text" name="lastname" /><br />
Address: <input type="text" name="address" /><br />
City: <input type="text" name="city" /><br />
</form>
background.html
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "firstname")
sendResponse({status: localStorage['firstname']});
else
sendResponse({});
});
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.method == "lastname")
sendResponse({status: localStorage['lastname']});
else
sendResponse({});
});
content.js
chrome.extension.sendRequest({method: "firstname"}, function(response) {
alert(response.status);
});
chrome.extension.sendRequest({method: "lastname"}, function(response) {
alert(response.status);
});
【问题讨论】:
-
如果您查看
options.html上的resources tab,您是否在localstorage 下看到了预期的数据? -
@abraham 是的,我可以在本地存储下的资源选项卡中查看所有数据,并且可以使用
Message Passing。我更新了代码,你能解释一下如何从本地存储中调用每条数据吗?我不知道如何调用它们。我只知道怎么叫一个。
标签: jquery html google-chrome-extension local-storage