想问下在Chrome扩展中使用Chrome提供的存储API可以实现表单存储吗?

大家,想要对用户输入的表单数据在浏览器端存储,用什么方法比较好啊?安全问题暂不考虑,没有任何敏感数据的。
尝试了使用Chrome localstorage API,但是没有成功。

再详细说一下要实现的功能:
在扩展中有2-3个输入框,对于用户多次在这些输入框中输入的不同的文本内容进行存储并且显示在扩展中。

可能说的不太准确,我再详细说一下我的需求:
有3个输入框,这三个输入框为一组数据,用户提交一次后会将数据保存在本地并且实时显示在浏览器中,用户第二次输入数据并提交的时候是添加一组数据而不是更新上一组数据。

谢谢关注者。。。

阅读 2.4k
3 个回答

直接给你段代码好了,自己看看改改

var strKey = "content_{{$question->id}}";

var storage = window.localStorage;
var docAnswer = document.getElementById("answer_editor_content");

if(docAnswer){
    //再次打开页面时尝试赋值
    if(docAnswer.value == "" && storage.getItem(strKey)!=null){
        $("#answer_editor_content").val(storage.getItem(strKey));
        $("#answer_editor").html(storage.getItem(strKey));
    }
    //定时保存
    setInterval("cacheContent()",1000);
}
function cacheContent(){
    var strValue = document.getElementById("answer_editor_content").value;
    if (storage && strValue != '') {
        storage.setItem(strKey, strValue);
    }
}

如果是写chrome扩展的话,可以使用storage这个api,会自动同步云端(如果你连接了谷歌服务器),否则和localstorage是一样的,可直接存储数组或对象。
具体使用

 chrome.storage.sync.set({ 'key': vlaue }, function() {
                console.log(' saved success');
  });
value可以为字符串,数组,对象,使用这个api需要在manifest.json中添加"storage"这个权限

如果是使用普通的sessionStorage或localStorage,存储复杂对象,可以把对象或数组用JSON.stringfy转成字符串来存储,使用的时候用JSON.parse来解析成原来的格式。
希望能对你有所帮助。

存cookie、session或者H5的localStorage、sessionStorage

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题