Javascript 在Google Chrome扩展选项面板的localStorage中保存数据并访问数据

Javascript 在Google Chrome扩展选项面板的localStorage中保存数据并访问数据,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我正在为Google Chrome制作一个插件,当用户点击它时,该插件会删除所有浏览数据,该插件工作正常,但现在我正在尝试添加一个选项面板,用户可以选择删除哪些数据,我的问题是,用户在选项面板中所做的选项没有被保存(或者我无法正确检索存储在localStorage中的数据),因为保存并关闭后再次访问选项面板时,复选框再次为空 Manifest[Manifest.json] { "name": "TEST TITLE", "version": "1.0", "manifest_vers

我正在为Google Chrome制作一个插件,当用户点击它时,该插件会删除所有浏览数据,该插件工作正常,但现在我正在尝试添加一个选项面板,用户可以选择删除哪些数据,我的问题是,用户在选项面板中所做的选项没有被保存(或者我无法正确检索存储在localStorage中的数据),因为保存并关闭后再次访问选项面板时,复选框再次为空

Manifest[Manifest.json]

{
  "name": "TEST TITLE",
  "version": "1.0",
  "manifest_version": 2,
  "description": "TEST DESCRIPTION",
  "options_page": "options.html",
  "icons": { "16": "icon-small.png",
            "48": "icon-medium.png",
            "128": "icon-big.png" },
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "storage",
    "browsingData"
  ]
}
HTML[弹出窗口.HTML]

<!DOCTYPE html>
<html>
  <head>
  <script src="script.js"></script>
  </head>
  <body>
  </body>
</html>
JavaScript[script options.js]

// JavaScript Document

function saveOptions() {
    if (document.getElementById('protectedWeb-checkbox').checked) {
        localStorage.setItem('protectedWeb-checkbox', "true");
    } else {
        localStorage.setItem('protectedWeb-checkbox', "false");
    }
}

function loadOptions() {
    if (localStorage.getItem('protectedWeb-checkbox') == "true") {
        console.log("its checked");
        document.getElementById("protectedWeb-checkbox").checked=true;
    } else {
        console.log("its not checked");
    }
}
除了主要问题之外,我还想知道您认为向JavaScript[script options.js]添加其他14个选项的最佳方式是什么,以及您建议我如何更改JavaScript[script.js]上的值(真/假)还可以使用JavaScript,如果您对整个扩展代码有任何建议或建议,我们将不胜感激

和往常一样,提前感谢您抽出时间阅读本文,下面的列表是我到目前为止阅读的所有StackOverflow问题和网站

https://stackoverflow.com/questions/3033829/google-chrome-extension-local-storage
https://stackoverflow.com/questions/2153070/do-chrome-extensions-have-access-to-local-storage
https://stackoverflow.com/questions/11679967/remember-checkbox-with-localstorage-onclick
http://julip.co/2010/01/how-to-build-a-chrome-extension-part-2-options-and-localstorage/
https://developer.chrome.com/stable/extensions/storage.html

您删除了popup.html中的所有localstorage数据。因此,每次打开它时,您的设置都会消失。如果您不打开它,则设置不会真正发挥作用。

在阅读了您的代码后,我准备了一个结构,您可以进一步扩展所有复选框

我已经在以下情况下对其进行了测试,如果您仍然有困难,请告诉我:

页面开头:

选择后

页面加载后:

刷新:

您可以使用chrome存储API代替本地存储

manifest.json

popup.html

脚本选项.js

//JavaScript文档 var存储=chrome.storage.local

function saveOptions() {
    console.log("Clicked ... ");
//Use document.querySelectorAll() function when you all multiple check boxes and iterate over them instead of huge if-else chains
    if (document.getElementById('protectedWeb').checked) {
        // Save it using the Chrome extension storage API.
        storage.set({'protectedWeb': 'true'}, function() {
            // Notify that we saved.
            console.log('Settings saved');
        });

    } else {
        // Save it using the Chrome extension storage API.
        storage.set({'protectedWeb': 'false'}, function() {
            // Notify that we saved.
            console.log('Settings saved');
        });
    }
}

function getSelectedData() {
    chrome.storage.local.get('protectedWeb',function (obj){
    if(obj.protectedWeb == "true"){
    document.getElementById('protectedWeb').checked = true;
}else{
    document.getElementById('protectedWeb').checked = false;
}
});
}

window.onload = function (){
    getSelectedData();
    document.getElementById('save').onclick=saveOptions;
}

这是我的贡献。
这样做是因为我讨厌做html/css;)
选项已自动保存,因此无需“保存”按钮。
注释掉弹出式按键上清除内容的位,不想清除任何内容。
manifest.json

{
  "name": "ProtectedWeb",
  "description" : "http://stackoverflow.com/questions/13617257/saving-data-in-localstorage-for-a-googlechrome-extension-options-panel-and-acces/",
  "version": "1.0",
  "permissions": [
    "tabs", "<all_urls>","storage","browsingData"
  ],
  "browser_action": {
      "default_title": "Clear stuff",
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  },
  "options_page": "options.html",
  "manifest_version":2
}
<html>
  <head>
  <script src="options.js"></script>
  </head>
  <body>
  <div id="wrapper-options">
  <div id="header-options">OPTIONS</div>
  <div id="content-options">
    <br />
    Origin Type
    <div id="originTypes">
    </div>
  <div id="checkbox-options">
    <br />
    Options
    <div id="options">
    </div>
  </div>
  </div>
  </div>
  </body>
</html>
// This is where we store the default options if there aren't any options saved and it gets replaced with what is saved on load if there is anything in storage
var Options = {
    "originTypes": {
        "protectedWeb": false,
        // Set to false or false as per your requirement / Websites that have been installed as hosted applications
        "unprotectedWeb": true,
        // Set to true or false as per your requirement / Normal websites
        "extension": false
        // Set to true or false as per your requirement / Extensions and packaged applications a user has installed
    },
    options: {
        "appcache": true,
        // Set to false or false as per your requirement / Websites appcaches
        "cache": true,
        // Set to false or false as per your requirement / Browser's cache
        "cookies": true,
        // Set to false or false as per your requirement / Browser's cookies
        "downloads": true,
        // Set to false or false as per your requirement / Browser's download
        "fileSystems": true,
        // Set to false or false as per your requirement / Websites file systems
        "formData": true,
        // Set to false or false as per your requirement / Browser's stored form data
        "history": true,
        // Set to false or false as per your requirement / Browser's history
        "indexedDB": true,
        // Set to false or false as per your requirement / Websites IndexedDB data
        "localStorage": true,
        // Set to false or false as per your requirement / Websites local storage data
        "pluginData": true,
        // Set to false or false as per your requirement / Plugins data
        "passwords": true,
        // Set to false or false as per your requirement / Stored passwords
        "webSQL": true
        // Set to false or false as per your requirement / Websites WebSQL data
    }
}


var optionsTemplate = {
    originTypes: [{
        name: "appcache",
        title: "appcache",
        description: "Websites appcaches"

    }, {
        name: "unprotectedWeb",
        title: "Unprotected Web",
        description: "Normal websites"

    }, {
        name: "extension",
        title: "Extension",
        description: "Extensions and packaged applications a user has installed"

    }],
    options: [{
        name: "appcache",
        title: "appcache",
        description: "Websites appcaches"

    }, {
        name: "cache",
        title: "cache",
        description: "Browser's cache"

    }, {
        name: "cookies",
        title: "cookies",
        description: "Browser's cookies"

    }, {
        name: "downloads",
        title: "downloads",
        description: "Browser's download"

    }, {
        name: "fileSystems",
        title: "fileSystems",
        description: "Websites file systems"

    }, {
        name: "formData",
        title: "formData",
        description: "Browser's stored form data"

    }, {
        name: "history",
        title: "history",
        description: "Browser's history"

    }, {
        name: "indexedDB",
        title: "indexedDB",
        description: "Websites IndexedDB data"

    }, {
        name: "localStorage",
        title: "localStorage",
        description: "Websites local storage data"

    }, {
        name: "pluginData",
        title: "pluginData",
        description: "Plugins data"

    }, {
        name: "passwords",
        title: "passwords",
        description: "Stored passwords"

    }, {
        name: "webSQL",
        title: "webSQL",
        description: "Websites WebSQL data"
    }]
}

var optionsTemplateSelectors = {
    originTypes: '#originTypes',
    options: '#options'
}


renderHTML = function(template, targets) {
    var key, keys, elements = {};
    keys = Object.keys(targets);
    for(var i = 0; i < keys.length; i++) {
        key = keys[i];
        elements[key] = document.querySelector(targets[key]);
        if (elements[key]===null) console.debug('Couldn\'t find "'+key+'"" using the querySelector "'+targets[key]+'"');
    }

    var sections = Object.keys(template),
        section;
    var item;
    var checkbox, div, text;
    for(var z = 0; z < sections.length; z++) {
        section = sections[z];
        for(var i = 0; i < template[section].length; i++) {
            item = template[section][i];
            div = document.createElement('div');
            text = document.createTextNode(item.title);
            checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = item.name + '-checkbox';
            checkbox.dataset['section'] = section;
            checkbox.dataset['key'] = item.name;
            checkbox.title = item.description;
            if(Options[section][item.name] === true) checkbox.checked = true;
            checkbox.addEventListener('change', checkboxChanged);
            div.id = item.name;
            div.appendChild(checkbox);
            div.appendChild(text);
            elements[section].appendChild(div);
        }
    }
}


checkboxChanged = function(evt) {
    var src = evt.srcElement;
    var checked = src.checked;
    Options[src.dataset['section']][src.dataset['key']] = checked;
    chrome.storage.local.set({
        'options': Options
    });
}


init = function() {
    chrome.storage.local.get('options', function(options) {
        if(Object.keys(options).length === 0) {
            chrome.storage.local.set({
                'options': Options
            });
        } else {
            Options = options.options;
        }
        renderHTML(optionsTemplate, optionsTemplateSelectors);
    })
}


window.addEventListener('load', init);
<!doctype html>
<html>
  <head>
    <script src="popup.js"></script>
  </head>
  <body>
  </body>
</html>
chrome.storage.local.get('options', function(data) {
    chrome.browsingData.remove({
  "originTypes":data.options.originTypes
},data.options.options);
});

//window.close();

哦,
optiontitlesscriptions
本来应该是“optiontitlesscriptions”……如果我现在能费心修好它的话,那就麻烦了;)还有哈。你的设置在每次弹出窗口时都会被你删除,因为你清除了浏览器历史记录/存储,包括那些属于你自己的扩展。谢谢你的回答@PAEz不幸的是,你的代码不起作用,它所做的只是在选项的复选框原来所在的位置打印一些内容。@Minnen很抱歉,忘记了{}不等于零,所以现在检查它的键长度。还更改了模板位,以便在我使用它时保持它的顺序和其他一些东西(我自己计划很快使用类似的东西,所以需要正确地使用它;)。希望它对你有用。……应该。@Minnen还应该指出,每个
原始类型
都可以有自己的
选项集
@Minnen抱歉,再一次。忘了将浏览数据添加到清单中,现在一切都可以工作了吗(我又去了,诱惑众神;)。这次我真的测试过了。顺便说一句,取消对该窗口的注释。如果您不想在他们单击浏览器操作时弹出窗口,请在弹出窗口中关闭。嗨@Sudarshan!,我测试了你的代码,但它不起作用,如果你刷新“选项”面板或只是保存“关闭”并重新打开它,选项仍然会消失。我仍然感谢您的关心。@Minnen:对不起,我忘了在代码中包含这一点,我已经添加了它;现在检查它,如果它仍然失败,请告诉我。@Sudarshan在您的saveOptions函数中,您应该使用
document.queryselectoral('input[type=“checkbox”]”)
来获取所有复选框的列表。然后遍历该列表,检查每个元素的checked值,并使用元素id知道要在存储器中设置什么。否则,您将最终得到一个巨大的功能,这将是一个痛苦的改变/维护。只是一个建议。@PAEz:是的,你是对的,我从一个复选框开始,然后结束,是的,维护明智的querySelectorAll()是最好的方法。@Sudarshan嗨!,我复制了整个代码并进行了测试,它仍然不起作用,我检查了每一行两次,以防我遗漏了一些东西,或者可能复制了一些错误或“脏”的东西,但它是完全相同的代码,真的不知道该说些什么我担心有人会认为,我没有在这个过程中运行扩展,这篇文章只涉及选项面板,我现在试图做的只是找到存储选项并稍后访问该数据的方法。
function saveOptions() {
    console.log("Clicked ... ");
//Use document.querySelectorAll() function when you all multiple check boxes and iterate over them instead of huge if-else chains
    if (document.getElementById('protectedWeb').checked) {
        // Save it using the Chrome extension storage API.
        storage.set({'protectedWeb': 'true'}, function() {
            // Notify that we saved.
            console.log('Settings saved');
        });

    } else {
        // Save it using the Chrome extension storage API.
        storage.set({'protectedWeb': 'false'}, function() {
            // Notify that we saved.
            console.log('Settings saved');
        });
    }
}

function getSelectedData() {
    chrome.storage.local.get('protectedWeb',function (obj){
    if(obj.protectedWeb == "true"){
    document.getElementById('protectedWeb').checked = true;
}else{
    document.getElementById('protectedWeb').checked = false;
}
});
}

window.onload = function (){
    getSelectedData();
    document.getElementById('save').onclick=saveOptions;
}
{
  "name": "ProtectedWeb",
  "description" : "http://stackoverflow.com/questions/13617257/saving-data-in-localstorage-for-a-googlechrome-extension-options-panel-and-acces/",
  "version": "1.0",
  "permissions": [
    "tabs", "<all_urls>","storage","browsingData"
  ],
  "browser_action": {
      "default_title": "Clear stuff",
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  },
  "options_page": "options.html",
  "manifest_version":2
}
<html>
  <head>
  <script src="options.js"></script>
  </head>
  <body>
  <div id="wrapper-options">
  <div id="header-options">OPTIONS</div>
  <div id="content-options">
    <br />
    Origin Type
    <div id="originTypes">
    </div>
  <div id="checkbox-options">
    <br />
    Options
    <div id="options">
    </div>
  </div>
  </div>
  </div>
  </body>
</html>
// This is where we store the default options if there aren't any options saved and it gets replaced with what is saved on load if there is anything in storage
var Options = {
    "originTypes": {
        "protectedWeb": false,
        // Set to false or false as per your requirement / Websites that have been installed as hosted applications
        "unprotectedWeb": true,
        // Set to true or false as per your requirement / Normal websites
        "extension": false
        // Set to true or false as per your requirement / Extensions and packaged applications a user has installed
    },
    options: {
        "appcache": true,
        // Set to false or false as per your requirement / Websites appcaches
        "cache": true,
        // Set to false or false as per your requirement / Browser's cache
        "cookies": true,
        // Set to false or false as per your requirement / Browser's cookies
        "downloads": true,
        // Set to false or false as per your requirement / Browser's download
        "fileSystems": true,
        // Set to false or false as per your requirement / Websites file systems
        "formData": true,
        // Set to false or false as per your requirement / Browser's stored form data
        "history": true,
        // Set to false or false as per your requirement / Browser's history
        "indexedDB": true,
        // Set to false or false as per your requirement / Websites IndexedDB data
        "localStorage": true,
        // Set to false or false as per your requirement / Websites local storage data
        "pluginData": true,
        // Set to false or false as per your requirement / Plugins data
        "passwords": true,
        // Set to false or false as per your requirement / Stored passwords
        "webSQL": true
        // Set to false or false as per your requirement / Websites WebSQL data
    }
}


var optionsTemplate = {
    originTypes: [{
        name: "appcache",
        title: "appcache",
        description: "Websites appcaches"

    }, {
        name: "unprotectedWeb",
        title: "Unprotected Web",
        description: "Normal websites"

    }, {
        name: "extension",
        title: "Extension",
        description: "Extensions and packaged applications a user has installed"

    }],
    options: [{
        name: "appcache",
        title: "appcache",
        description: "Websites appcaches"

    }, {
        name: "cache",
        title: "cache",
        description: "Browser's cache"

    }, {
        name: "cookies",
        title: "cookies",
        description: "Browser's cookies"

    }, {
        name: "downloads",
        title: "downloads",
        description: "Browser's download"

    }, {
        name: "fileSystems",
        title: "fileSystems",
        description: "Websites file systems"

    }, {
        name: "formData",
        title: "formData",
        description: "Browser's stored form data"

    }, {
        name: "history",
        title: "history",
        description: "Browser's history"

    }, {
        name: "indexedDB",
        title: "indexedDB",
        description: "Websites IndexedDB data"

    }, {
        name: "localStorage",
        title: "localStorage",
        description: "Websites local storage data"

    }, {
        name: "pluginData",
        title: "pluginData",
        description: "Plugins data"

    }, {
        name: "passwords",
        title: "passwords",
        description: "Stored passwords"

    }, {
        name: "webSQL",
        title: "webSQL",
        description: "Websites WebSQL data"
    }]
}

var optionsTemplateSelectors = {
    originTypes: '#originTypes',
    options: '#options'
}


renderHTML = function(template, targets) {
    var key, keys, elements = {};
    keys = Object.keys(targets);
    for(var i = 0; i < keys.length; i++) {
        key = keys[i];
        elements[key] = document.querySelector(targets[key]);
        if (elements[key]===null) console.debug('Couldn\'t find "'+key+'"" using the querySelector "'+targets[key]+'"');
    }

    var sections = Object.keys(template),
        section;
    var item;
    var checkbox, div, text;
    for(var z = 0; z < sections.length; z++) {
        section = sections[z];
        for(var i = 0; i < template[section].length; i++) {
            item = template[section][i];
            div = document.createElement('div');
            text = document.createTextNode(item.title);
            checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.id = item.name + '-checkbox';
            checkbox.dataset['section'] = section;
            checkbox.dataset['key'] = item.name;
            checkbox.title = item.description;
            if(Options[section][item.name] === true) checkbox.checked = true;
            checkbox.addEventListener('change', checkboxChanged);
            div.id = item.name;
            div.appendChild(checkbox);
            div.appendChild(text);
            elements[section].appendChild(div);
        }
    }
}


checkboxChanged = function(evt) {
    var src = evt.srcElement;
    var checked = src.checked;
    Options[src.dataset['section']][src.dataset['key']] = checked;
    chrome.storage.local.set({
        'options': Options
    });
}


init = function() {
    chrome.storage.local.get('options', function(options) {
        if(Object.keys(options).length === 0) {
            chrome.storage.local.set({
                'options': Options
            });
        } else {
            Options = options.options;
        }
        renderHTML(optionsTemplate, optionsTemplateSelectors);
    })
}


window.addEventListener('load', init);
<!doctype html>
<html>
  <head>
    <script src="popup.js"></script>
  </head>
  <body>
  </body>
</html>
chrome.storage.local.get('options', function(data) {
    chrome.browsingData.remove({
  "originTypes":data.options.originTypes
},data.options.options);
});

//window.close();