Chrome extension - Localstorage not working

Posted by Bjarki Jonasson on Stack Overflow See other posts from Stack Overflow or by Bjarki Jonasson
Published on 2011-03-16T09:54:16Z Indexed on 2011/03/20 8:09 UTC
Read the original article Hit count: 247

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about google-chrome