2

I am working on a chrome extension and I am able to successfully store information to local storage, but my issue is actually access that information once it's in local storage. What I have not does not return anything just says NULL.

I have two files: options.html, and content.js. The options.html is where the user will input the information to save to local storage and the content.js will access the information to use.

options.html

$(function() {
    // Insert new buttons (you'd probably not ACTUALLY use buttons, instead saving on blurs or every x seconds)
    $("#save_buttons").after("<input type='submit' value='Save Form' id='saveData'>").after("<input type='submit' value='Clear Saved Data' id='clearData'>");
    $("#saveData").click(function(e) {
        // Don't actually submit form
        e.preventDefault();

        // Bit of generic data to test if saved data exists on page load
        localStorage.setItem("flag", "set");

        // serializeArray is awesome and powerful
        var data = $("#hanes").serializeArray();

        // iterate over results
        $.each(data, function(i, obj) {
            // HTML5 magic!!
            localStorage.setItem(obj.name, obj.value);
        });
    });

    // Test if there is already saved data  
    if (localStorage.getItem("flag") == "set") {
        // Tell the user
        $("header").before("<p id='message'>This form has saved data!</p>");

        // Same iteration stuff as before
        var data = $("#hanes").serializeArray();

        // Only the only way we can select is by the name attribute, but jQuery is down with that.
        $.each(data, function(i, obj) {
            $("[name='" + obj.name +"']").val(localStorage.getItem(obj.name));
        });
    }

    // Provide mechanism to remove data. You'd probably actually remove it not just kill the flag
    $("#clearData").click(function(e) {
        e.preventDefault();
        localStorage.setItem("flag", "");
    });
});


<form id="hanes" name="hanes">
First name: <input type="text" name="firstname" id="firstname" /><br />
Last name: <input type="text" name="lastname" /><br />
Address: <input type="text" name="address" /><br />
City: <input type="text" name="city" /><br />
</form>

background.html

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

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

content.js

chrome.extension.sendRequest({method: "firstname"}, function(response) {
  alert(response.status);
});

chrome.extension.sendRequest({method: "lastname"}, function(response) {
  alert(response.status);
});
Daniel
  • 4,202
  • 11
  • 50
  • 68
  • If you look at the [resources tab](https://developers.google.com/chrome-developer-tools/docs/resources) on `options.html` do you see the data as expected under localstorage? – abraham Apr 09 '12 at 04:36
  • @abraham Yes, I am able to see all data in the resources tab under local storage, and I am able to get it working with `Message Passing`. I updated the code can you explain how I can call each piece of data from the local storage I don't know how to call them all. I only know how to call one. – Daniel Apr 09 '12 at 19:04

2 Answers2

5

Content scripts run in their own little world thats even outside the world of your extension ( Chrome extension code vs Content scripts vs Injected scripts). Content scripts are unable to access the localStorage of your extension.
So you either need to communicate with the background page using message passing ( http://code.google.com/chrome/extensions/messaging.html) or if you really want to avoid using a background page you can use the iFrame trick ( Options-enabled content-script Chrome extension without background page?).

Community
  • 1
  • 1
PAEz
  • 8,366
  • 2
  • 34
  • 27
  • Abraham is right about using the parentheses instead of brackets, but this is the answer. `localStorage` in a Content Script refers to the `localStorage` of the page on which it is injected. – Rob W Apr 09 '12 at 09:48
  • @PAEz `message passing` works thank you, but how do I access all the data in local storage? I updated my code. – Daniel Apr 09 '12 at 19:29
  • @Mr.1.0 I didnt try your code, but that looks right to me. If your asking how to access all of localStorage in one call I guess you could do `JSON.stringify(localStorage)` and send that back to the content script. Although normally Id just make an object with everything I wanted and send that stringified to the content script. – PAEz Apr 09 '12 at 19:43
0

Use () instead of [].

var fname = window.localStorage.getItem('firstname');
abraham
  • 46,583
  • 10
  • 100
  • 152