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

查看:30
本文介绍了如何在我的 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 的 storage 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" } ]
});

有关这些恶作剧如何运作的更多信息: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.谷歌浏览器实现了 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天全站免登陆