如何在我的 chrome 扩展中保存本地信息?

我想我的铬扩展保存一些信息,我不知道如何开始的代码..。 我需要它来节省绳子。 例如-用户输入一个字符串(在弹出窗口的文本区域中) ,这个字符串显示在弹出窗口中。当用户退出并返回时,我希望字符串保持不变。 (我相信它必须拯救它) 我不想保存在我的服务器或类似的东西,我希望它被保存在用户缓存或东西。

84833 次浏览

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" } ]
});

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

Former answer:

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.

There is a specific API now, check this here: https://developer.chrome.com/extensions/storage

Note that it is only available on your background page and works in an isolated world (you don't access the values contained in the HTML5 localStorage of the web site).