Chrome插件保存复选框失败选项页面



我无法使用chrome.storage.sync保护新chrome插件中选项页面的复选框数据。我已经尝试了很多方法来使其能够工作;这是我最新的一个。我完全迷失了。提前致谢:

$(document).ready(function () {
  var storage = chrome.storage.sync;
  function load_options() {
    //Retrieve existing settings
    $("input[type=checkbox]").each(function() {
      $(this).prop('checked', function() {
        var name = $(this).parent().next().html();
        storage.get(name, function(items){
          element.checked = items[name];
        });
      });
    });
  }
  function saveSettings() {
    var checkboxes = $("input[type=checkbox]");
    var items = {};
    checkboxes.each(function (){
      var name = $(this).parent().next().html();
      items[name] = this.checked;
    });
    storage.set(items, function() {
      console.log("saved");
     });
} 
  //Factory settings pages class, load dynamic html
  function SettingsPageFactory(menuitem) {
    this.settingsFactoryItems = {
      Posts: 'settings/posts.html',
      Sidebar: 'settings/sidebar.html',
      General: 'settings/general.html',
      Privacy: 'settings/privacy.html'
    };
    this.keys = [];
    for (var key in this.settingsFactoryItems) {
      this.keys.push(key);
    }

    this.createSettingsPage = function () {
      var key = menuitem.find("a").html();
      currentPage = key;
      if ($.inArray(this.keys, key)) {
        $("#page-content-wrapper").html("");
        var url = chrome.runtime.getURL(this.settingsFactoryItems[key]);
        return url;
      }
    }
  }
  $("#wrapper").on("click", "a#safeman.btn.btn-info", function () {
    saveSettings();
  });
  $(".menuitem").on("click", function () {
    var settingsPageFactory = new SettingsPageFactory($(this));
    var url = settingsPageFactory.createSettingsPage();
    $("#page-content-wrapper").load(url + " .container-fluid");
    load_options();
    return false;
  });

所需的行为只是一个选项页面,其中包含异步加载的不同页面。这些包含看起来像开关的复选框。打开或关闭开关时,必须使用上述 API 保存。动态页面都包含在此主页中:

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, shrink-to-fit=no, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">
  <title>Faceblock - Settings Page</title>
  <!-- Bootstrap Core CSS -->
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <!-- Switch checkbox -->
  <link href="css/switchbox.css" rel="stylesheet" />

  <!-- Custom CSS -->
  <link href="css/simple-sidebar.css" rel="stylesheet">
  <link href="css/options.css" rel="stylesheet">

</head>
<body>
  <div id="wrapper">
    <!-- Sidebar -->
    <div id="sidebar-wrapper">
      <ul class="sidebar-nav">
        <li class="sidebar-brand">
          <a href="options.html" style="text-align:center;margin-left:-30px;">
                        Settings
                    </a>
        </li>
        <li class="menuitem">
          <span class="glyphicon glyphicon-download-alt"></span><a href="posts">Posts</a>
        </li>
        <li class="menuitem">
          <span class="glyphicon glyphicon-indent-right"></span>
          <a href="sidebar">Sidebar</a>
        </li>
        <li class="menuitem"><span class="glyphicon glyphicon-eye-close"></span>
          <a href="privacy">Privacy</a>
        </li>
        <li class="menuitem">
          <span class="glyphicon glyphicon-check"></span>
          <a href="general">General</a>
        </li>
        <li class="menuitem">
          <span class="glyphicon glyphicon-eur"></span>
          <a href="donate">Donate</a>
        </li>
        <li class="menuitem">
          <span class="glyphicon glyphicon-cog"></span>
          <a href="settings">Settings</a>
        </li>
      </ul>
    </div>
    <!-- /#sidebar-wrapper -->
    <!-- Page Content -->
    <div id="page-content-wrapper">
      <div class="container-fluid">
        <div class="row content">
          <div class="col-lg-12">
            <a href="#menu-toggle" class="btn btn-black" id="menu-toggle">Toggle Menu</a>
            <h2>Faceblock Settings Page</h2>
            <p>Faceblock is a Chrome extension which filters all annoying adds on Facebook. It also gives you control over which content you would like to show or hide, and makes sure your privacy is kept secret to big companies.</p>
            <p>If you like our Chrome plugin, feel free to donate a small fee in order to keep future changes and features coming. <code>Choose a category from the right sidebar and start configuring Facebook according to your needs!</code></p>
          </div>
        </div>
      </div>
    </div>
    <!-- /#page-content-wrapper -->
  </div>
  <div id="dependencies" />
  <script src="js/jquery.min.js"></script>
  <!-- Bootstrap Core JavaScript -->
  <script src="js/bootstrap.min.js"></script>
  <script src="js/background.js"></script>
  <script src="js/options.js"></script>
  </div>
  <!-- /#wrapper -->

</body>
</html>

动态加载页面的示例可在此处找到:

<div class="container-fluid">
  <div class="row content">
    <div class="col-lg-12">
      <a href="#menu-toggle" class="btn btn-black" id="menu-toggle">Toggle Menu</a>
      <div class="container">
        <div class="col-lg-1 col-centered">

        </div>
        <h2>privacy</h2>
      </div>
      <p>Facebook stores unwanted data in the form of cookies and other ways to show you unwanted data you might like.<code>At this page you can tell Facebook to not store your private information and to not sell it to its third-party apps.</code></p>
      <div class="container">
        <div class="col-lg-1 col-centered">
          <label class="switch ">
  <input type="checkbox" checked>
  <div class="slider round"></div>
</label>
          <div class="lable">Disable cookies Facebook</div>
        </div>
      </div>

    </div>
  </div>
</div>

我的清单.json看起来像这样:

    {
      "name": "FaceBlock",
      "description": "This extention gets rid of unwanted content on Facebook like sponsored posts, adds or annoying suggestions. The content you wish to see is enlarged for a better and richer social experience.",
      "version": "0.0.1",
      "manifest_version": 2,
      "content_scripts": [
        {
          "matches": [
        "http://*.facebook.com/*", "https://*.facebook.com/*", "<all_urls>"],
          "css": ["css/popup.css"],
          "js": ["js/jquery.min.js", "js/content.js",
          "js/options.js",
          "js/background.js"],
          "run_at": "document_end",
          "all_frames": true
    }],
      "options_page": "options.html",
      "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html",
        "default_title": "Faceblock"
      },
      "permissions": [
    "activeTab",
    "tabs",
    "https://www.facebook.com/*",
    "https://ajax.googleapis.com/",
    "storage",
    "<all_urls>"
  ],
      "background": {
        "scripts": ["js/background.js", "js/options.js"],
        "persistent": true
      },
      "options_ui": {
        // Required.
        "page": "options.html",
        // Recommended.
        "chrome_style": true
          // Not recommended; only provided for backwards compatibility,
          // and will be unsupported in a future version of Chrome (TBD).
          //"open_in_tab": true
      },
      "web_accessible_resources": [
    "images/faceblock.jpg",
    "images/seigaiha.png",
    "js/popup.js",
    "icon.png",
    "js/options.js",
    "css/popup.css",
    "popup.html",
    "options.html",
    "background.html",
    "js/background.js"
  ]
    }

如下所述,我的load_options()可能会出现问题

问题在于保存和检索持久化的数据。解决方案如下:

保存设置

  function saveSettings() {
    var checkboxes = $("input[type=checkbox]");
    var items = {};
    checkboxes.each(function (){
      var name = $(this).parent().next().html();
      items[name] = this.checked;
      storage.set(items, function() {
        console.log("saved a checkbox");
      });
    });
}

我将一些代码转换为 jQuery,并确保将每个名称的复选框添加到 items 对象,然后持久化。

第二个错误对我来说有点复杂。由于我在加载可以加载持久内容的复选框之前异步加载了内容,因此首先通过回调加载内容对我来说非常重要。

$("#page-content-wrapper").load(url + " .container-fluid", load_options);

剩下的很简单,我将javascript从互联网示例更改为jQuery,并确保我检索到每个复选框的名称,然后将其与正在存储的项目进行比较。下面的解决方案可以使用一些错误处理。

function load_options() {
    //Retrieve existing settings
    console.log($("input[type=checkbox]").length);
    $("input[type=checkbox]").each(function() {
        var checkbox = $(this);
        var name = checkbox.parent().next().html();
        storage.get(name, function(items){
            console.log(items);
            checkbox.prop('checked', items[name]);
        });
      });
  }

最新更新