Chrome 扩展程序 - 本地存储不起作用

发布于 2024-10-22 02:31:35 字数 2142 浏览 4 评论 0原文

我正在编写一个 Chrome 扩展程序,它使用内容脚本来修改网站的某些部分。内容脚本工作正常,直到我尝试向我的扩展添加选项页面。

现在,我正在使用 options.html 文件将用户首选项保存到本地存储,如您在此处看到的:

    <html>
    <head><title>Options</title></head>
        <script type="text/javascript">

        function save_options() {
            var select = document.getElementById("width");
            var width = select.children[select.selectedIndex].value;
            localStorage["site_width"] = width;
        }

        function restore_options() {
          var fwidth = localStorage["site_width"];
          if (!fwidth) {
            return;
          }
          var select = document.getElementById("width");
          for (var i = 0; i < select.children.length; i++) {
            var child = select.children[i];
            if (child.value == fwidth) {
              child.selected = "true";
              break;
            }
          }
        }

        </script>

    <body onload="restore_options()">

    Width:
        <select id="width">
            <option value="100%">100%</option>
            <option value="90%">90%</option>
            <option value="80%">80%</option>
            <option value="70%">70%</option>
        </select>

        <br>
        <button onclick="save_options()">Save</button>
    </body>
</html>

我还有一个 background.html 文件来处理内容脚本和本地存储之间的通信:

<html>
    <script type="text/javascript">

        chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
            if (request.method == "siteWidth")
                sendResponse({status: localStorage["site_width"]});
            else
                sendResponse({});
        });

    </script>
</html>

然后是实际的内容脚本看起来像这样:

var Width;

chrome.extension.sendRequest({method: "siteWidth"}, function(response) {
        width = response.status;
    });

这些代码实际上都不起作用。对我来说它看起来足够可靠,但我不是一个非常有经验的程序员,所以我可能是错的。

有人可以用通俗易懂的方式向我解释本地存储吗?

I'm writing a Chrome extension that uses a content script to modify certain parts of a website. The content script worked fine until I tried to add an options page to my extension.

Right now I'm using an options.html file to save user preferences to localstorage, as you can see here:

    <html>
    <head><title>Options</title></head>
        <script type="text/javascript">

        function save_options() {
            var select = document.getElementById("width");
            var width = select.children[select.selectedIndex].value;
            localStorage["site_width"] = width;
        }

        function restore_options() {
          var fwidth = localStorage["site_width"];
          if (!fwidth) {
            return;
          }
          var select = document.getElementById("width");
          for (var i = 0; i < select.children.length; i++) {
            var child = select.children[i];
            if (child.value == fwidth) {
              child.selected = "true";
              break;
            }
          }
        }

        </script>

    <body onload="restore_options()">

    Width:
        <select id="width">
            <option value="100%">100%</option>
            <option value="90%">90%</option>
            <option value="80%">80%</option>
            <option value="70%">70%</option>
        </select>

        <br>
        <button onclick="save_options()">Save</button>
    </body>
</html>

I also have a background.html file to handle the communication between the content script and the localstorage:

<html>
    <script type="text/javascript">

        chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
            if (request.method == "siteWidth")
                sendResponse({status: localStorage["site_width"]});
            else
                sendResponse({});
        });

    </script>
</html>

Then there's the actual content script that looks like this:

var Width;

chrome.extension.sendRequest({method: "siteWidth"}, function(response) {
        width = response.status;
    });

None of that code actually works. It looks solid enough to me but I'm not a very experienced programmer so I might be wrong.

Could someone explain localstorage to me in layman's terms?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

人心善变 2024-10-29 02:31:35

window.localStorage 具有需要使用的 getter 和 setter 来访问内部对象映射。

因此,要设置:

localStorage.setItem(key, value);

要获取:

localStorage.getItem(key);

要清除地图:

localStorage.clear();

要删除项目:

localStorage.removeItem(key);

要获取长度:

localStorage.length

要基于内部地图中的索引键入:

localStorage.key(index);

要阅读更多信息: http://dev.w3.org/html5/webstorage/#the-storage-interface

window.localStorage实现Storage接口:

interface Storage {
 readonly attribute unsigned long length;
 DOMString key(in unsigned long index);
 getter any getItem(in DOMString key);
 setter creator void setItem(in DOMString key, in any value);
 deleter void removeItem(in DOMString key);
 void clear();
};

The window.localStorage has getters and setters that need to be used in order to access the internal object map.

So, to set:

localStorage.setItem(key, value);

To get:

localStorage.getItem(key);

To clear map:

localStorage.clear();

To remove item:

localStorage.removeItem(key);

To get length:

localStorage.length

To key based on index in internal map:

localStorage.key(index);

To read more: http://dev.w3.org/html5/webstorage/#the-storage-interface

The window.localStorage implements the Storage interface:

interface Storage {
 readonly attribute unsigned long length;
 DOMString key(in unsigned long index);
 getter any getItem(in DOMString key);
 setter creator void setItem(in DOMString key, in any value);
 deleter void removeItem(in DOMString key);
 void clear();
};
悲歌长辞 2024-10-29 02:31:35

要详细了解 localStorage 的工作原理 有关 LocalStorage 的完整详细信息 是您入门的一个很好的来源。只是补充一下,我会给你一个可能对你有帮助的例子。这是options.html

<html>
<head>
<script type='text/javscript'>
function save_options() {
    if(document.getElementById("x").checked == true){localStorage['x_en'] = 1;}
    if(document.getElementById("x").checked == false){localStorage['x_en'] = 0;}
}

function restore_options() {
  var x_opt = localStorage['x_en'];
  if (x_opt == 0) {document.getElementById('x').checked = false;}else{
     var select = document.getElementById('x');select.checked = true; localStorage['x_en'] = 1;}
}
</script>
</head>

<body onload="restore_options()">
<table border="0" cellspacing="5" cellpadding="5" align="center">
    <tr class='odd'><td><input type='checkbox' id='x' onclick="save_options()"/></td><td>X</td></tr>
</table>

要访问它,您需要有一个 background.html 页面,如下所示。

alert(localStorage['x_en']); //Will alert the localStorage value.

如果您想从内容脚本访问 localStorage,则无法通过上述方法直接访问它。您需要使用称为消息传递的概念 (http://code.google.com/chrome /extensions/messaging.html),它可以将值从后台传递到内容脚本。正如谢尔盖所​​说,这可能是打字错误的问题。

To learn how localStorage works and in detail Complete details about LocalStorage is a good source for you to begin with. Just to add I will give you an example which might help you. This is the options.html

<html>
<head>
<script type='text/javscript'>
function save_options() {
    if(document.getElementById("x").checked == true){localStorage['x_en'] = 1;}
    if(document.getElementById("x").checked == false){localStorage['x_en'] = 0;}
}

function restore_options() {
  var x_opt = localStorage['x_en'];
  if (x_opt == 0) {document.getElementById('x').checked = false;}else{
     var select = document.getElementById('x');select.checked = true; localStorage['x_en'] = 1;}
}
</script>
</head>

<body onload="restore_options()">
<table border="0" cellspacing="5" cellpadding="5" align="center">
    <tr class='odd'><td><input type='checkbox' id='x' onclick="save_options()"/></td><td>X</td></tr>
</table>

To access this you need to have a background.html page which can be as shown below.

alert(localStorage['x_en']); //Will alert the localStorage value.

If you want to access the localStorage from the Content Script you can't directly access it by the above method. You need to use the concept called Message Passing (http://code.google.com/chrome/extensions/messaging.html) which can pass the values from the background to content scripts. Just as Sergey said this might be an issue with the typo.

秋凉 2024-10-29 02:31:35

使用访问器不是强制性的,可以随意使用 [] 运算符来获取和设置值,并使用“in”运算符来测试键是否存在。

但是,您的内容脚本中似乎存在拼写错误:

var 宽度;

chrome.extension.sendRequest({方法:
“站点宽度”},函数(响应){
宽度 = 响应.status;
});

由于 JavaScript 区分大小写,因此这两个是不同的变量。

Using accessors isn’t mandatory, feel free to use [] operator to get and set values, and “in” operator to test if key exists.

However, it looks like there’s a typo in your content script:

var Width;

chrome.extension.sendRequest({method:
"siteWidth"}, function(response) {
width = response.status;
});

Since JavaScript is case-sensitive, these two are different variables.

£冰雨忧蓝° 2024-10-29 02:31:35

尝试使用 window.localStorage.getItem/setItem 而不是 localStorage["site_width"]

try using window.localStorage.getItem/setItem instead of localStorage["site_width"]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文