2017-09-01 118 views
1

您可以使用browser.storage.local.set存储数组,还是使用不同的方法实现相同的结果?Firefox WebExtension,将数组存储在浏览器的存储器中

详情:

我的分机当前会重定向通过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"); 
} 
+1

是。你有没有试过存储数组? –

+1

[用chrome.storage.local存储数组]可能重复(https://stackoverflow.com/questions/16605706/store-an-array-with-chrome-storage-local) –

+0

为什么你认为你可能不会能够存储数组?认真。我希望能够更改文档,以便其他人不会产生混淆。我试图找到可以改进文档的位置,以防止其他人获得这种印象。 – Makyen

回答

0

新鲜的眼光已经解决了我的问题。

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