我如何在本地chrome扩展中保存信息? [英] How can I save information locally in my chrome extension?

查看:111
本文介绍了我如何在本地chrome扩展中保存信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的Chrome扩展保存一些信息,并且我不知道如何启动代码...
我需要它来保存字符串。
例如 - 用户输入一个字符串(在弹出框上的文本区域),该字符串显示在弹出窗口中。当用户退出并返回时,我希望字符串保持不变。
(我相信它必须保存它)
我不想将它保存在我的服务器或类似的东西上,我希望它保存在用户缓存或其他东西上。

I want my chrome extension to save some information, and I'm not sure how to start the code... I need it to save strings. For example - The user inputs a string (In a text area over the popup) and this string is shown on the popup. When the user exits it and returns I want the string to remain the same. (I belive it has to save it) I don't want to save it on my server or anything like that, I want it to be saved on the users cache or something.

推荐答案

现在,您可以利用Google Chrome的存储 API来执行此操作。与 localStorage 不同,它也可以从内容脚本访问。

You can now leverage Google Chrome's storage API to do this as well. Unlike localStorage, this is accessible from content scripts as well.

//  Somewhere in your manifest...

{
    "permissions": [
        "storage"
    ]
}

//  Usage:

//  PERSISTENT Storage - Globally
//  Save data to storage across their browsers...

chrome.storage.sync.set({ "yourBody": "myBody" }, function(){
    //  A data saved callback omg so fancy
});

chrome.storage.sync.get(/* String or Array */["yourBody"], function(items){
    //  items = [ { "yourBody": "myBody" } ]
});

//  LOCAL Storage

// Save data to storage locally, in just this browser...

chrome.storage.local.set({ "phasersTo": "awesome" }, function(){
    //  Data's been saved boys and girls, go on home
});

chrome.storage.local.get(/* String or Array */["phasersTo"], function(items){
    //  items = [ { "phasersTo": "awesome" } ]
});

更多信息如何在这里使用shenanigans: https://developer.chrome.com/extensions/storage#type-StorageArea

More info on how these shenanigans work here: https://developer.chrome.com/extensions/storage#type-StorageArea

以前的答案:

使用 localStorage 。 Google Chrome实现了HTML5的一些功能,它就是其中之一。

Use localStorage. Google Chrome implements some features of HTML5, and it is one of them.

//Pull text from user inputbox
var data = document.getElementById("this_input").value;
//Save it to the localStorage variable which will always remember what you store in it
localStorage["inputText"] = data; 

您应该注意,您只能从后台页面访问存储空间(无内容脚本)将不得不使用消息传递。

You should note you can only access your storage from the background page (no content scripts) so you'll have to use messaging for that.

这篇关于我如何在本地chrome扩展中保存信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆