javascript - 在 Chrome 扩展中存储数组

标签 javascript json google-chrome local-storage

我目前正在制作一个 Chrome 扩展程序,目前正处于最后阶段,即存储用户首选项。
我知道本地存储将存储字符串,在这个阶段,我对仅使用字符串感到困惑,但随着存储需求变得更大,需要一个二维数组。我已经看到本地存储无法存储数组,但您可以使用 JSON。我从未使用过 JSON,在查看示例时,我不明白该怎么做。

for (i=1;i<=localStorage["totalwebsites"];i++) {
        // Get the title of the current item
        var title = localStorage["websitetitle" + i];
        // Create the new context menu item, and get its menuItemId to store in the right localStorage string
        var menuItemId = chrome.contextMenus.create({parentId: ParentID, title: title, contexts:["selection"], onclick: searchFromContext});
        // Store the created menu items menuItemId in the array so we know which item was chosen later on
        websitesarray[menuItemId] = localStorage["websiteurl" + i];
    }

正如您所看到的,当使用字符串时,这会变得非常困惑、非常快。我希望totalwebsites成为数组中项目的计数,而websitetitle和websiteurl成为二维数组。
我不知道如何在 JSON 中执行此操作,或者至少不知道如何将其永久存储在 Chrome 本身中。我猜你必须在某个时候将其转换回本地存储字符串?我不认为我明白这一点。
任何帮助/指示将不胜感激,我找不到太多:(

最佳答案

别担心,JSON 非常简单!假设您的网站存储在 websitesarray 中:

// To load:
websitesarray = JSON.parse(localstorage.websites);

// To store:
localstorage.websites = JSON.stringify(websitesarray);

确保您有一个合理的方法来处理尚未设置 localstorage.websites 的情况,因为如果输入为 JSON.parse 将会抛出异常空。

关于javascript - 在 Chrome 扩展中存储数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8565379/

相关文章:

javascript - Backbone : Collection not rendered in View even though it's fetched

javascript - 可以是 String 或 Boolean 的 Spring 和 Json 字段映射

javascript - 查找 JSON 值是否包含特定文本

javascript - Chrome 中的表单问题

javascript - 如何为在 Chrome 中应用了 css 缩放的 img 获得正确的 jQuery offset()

google-chrome - 检测 Chrome 扩展程序首次运行/更新

javascript - 插入笑脸文字并播放图像

javascript - jquery 移动网络应用程序在页面底部留下空白区域

javascript - 如何在 Scala.js 中使用 AngularJS 的模块配置?

javascript - 添加和删​​除 JSON 对象的函数