【问题标题】:Firefox WebExtension, store an array in the browser's storageFirefox WebExtension,在浏览器的存储中存储一个数组
【发布时间】:2018-02-10 21:03:29
【问题描述】:

您能否使用browser.storage.local.set 存储数组或使用不同的方法获得相同的结果?

详情:

我的扩展程序目前将重定向通过 options.html 表单指定的网站。目前,当您指定新网站时,旧网站将被替换。有没有办法可以附加到将被重定向而不是替换网站的网站数组?

options.js:(将处理options.html中表单的信息)

function saveOptions(e) {
    e.preventDefault();
    browser.storage.local.set({
        url: document.querySelector("#url").value
    });
}
function restoreOptions() {
    function setCurrentChoice(result) {
        document.querySelector("#url").value = result.url || "reddit.com";
    }
    function onError(error) {
        console.log(`Error: ${error}`);
    }
    var getting = browser.storage.local.get("url");
    getting.then(setCurrentChoice, onError);
}
document.addEventListener("DOMContentLoaded", restoreOptions);
document.querySelector("form").addEventListener("submit", saveOptions);

redirect.js:

function onError(error) {
    console.log(`Error: ${error}`);
}
function onGot(item) {
    var url = "reddit.com";
    if (item.url) {
        url = item.url;
    }
    var host = window.location.hostname;
    if ((host == url) || (host == ("www." + url))) {
        window.location = chrome.runtime.getURL("redirect/redirect.html");
    }
}
var getting = browser.storage.local.get("url");
getting.then(onGot, onError);

我的想法是为每个 url 添加一个存储位置,但是 i 也必须被存储以防止它在每次加载 options.js 时被重置。 (类似于下面的代码)

var i = 0;
browser.storage.local.set({
    url[i]: document.querySelector("#url").value
});
i++;

更合乎逻辑的解决方案是将url 存储位置设为一个数组。

如果url 有办法成为一个数组,那么redirect.html 可以包含以下内容:

if ( (url.includes (host) ) || (url.includes ("www." + host) ) ){
    window.location = chrome.runtime.getURL("redirect.html");
}

【问题讨论】:

  • 是的。你试过存储一个数组吗?
  • 为什么您认为您可能无法存储数组?严重地。我希望能够更改文档,以便其他人不会有这种困惑。我正在努力寻找可以改进文档的地方,以防止其他人产生这种印象。
  • @Makyen 我认为问题可能是眼睛疲劳。再次查看文档后,chrome (link) 和 mozilla (link) 都清楚地表明您可以存储数组。

标签: javascript firefox-addon-webextensions


【解决方案1】:

新鲜的眼睛解决了我的问题。

在 options.js 中:

function saveOptions(e) {
    e.preventDefault();
    var array = (document.querySelector("#url").value).split(",");
    browser.storage.local.set({
        url: array
    });

在redirect.js中:

function onGot(item) {
    var url = "";
    if (item.url) {
        url = item.url;
    }
    var host = window.location.hostname;
    if ( (url.includes(host)) || (url.includes("www." + host)) ) {
        window.location = chrome.runtime.getURL("redirect/redirect.html");
    }   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-26
    • 2011-04-22
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2012-07-15
    • 2017-10-19
    相关资源
    最近更新 更多