Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Get value from localStorage to use in popup.html


I'm creating my first chrome extension and have gotten to a stage I can't seem to figure out.

Basically I can get my option to save, but I don't know how to retrieve the value to use it in popup.html

Here's my code:

manifest.json

{
"manifest_version": 2,
"name": "My Extension",
"options_page": "options.html",

"permissions": [
      "storage"
    ],

"description": "My Extension",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
   }
}

options.js

// Save options to localStorage.
function save_options()
{
  localStorage["url"] = document.getElementById("url").value;

  // Let the user know the options were saved.
  var status = document.getElementById("status");
  status.innerHTML = "Saved OK";
  setTimeout( function() { status.innerHTML = ""; }, 5000 );
}

// Populate options from from localStorage.
function load_options()
{
  var url = localStorage["url"];
  if (url == null) { url = ""; }
  document.getElementById("url").value = url;
}

// call load_options top populate the GUI when the DOM has loaded
document.addEventListener('DOMContentLoaded', load_options);

// call save_options when the user clicks the save button
document.getElementById("save").addEventListener('click', save_options);

options.html

<html>
<head>
<head><title>My Options</title></head>
<body>
    <div class="container">

        <label for="url">
            <p>My URL</p>
            <input type="text" id="url" />
            <button id="save">Save</button>
        </label>

    </div>

    <div id="status"></div>

</body>
<script src="options.js"></script>
</html>

popup.html

<html>
<head>
</head>
<body>
<iframe src="myURL" id="myURL" name="myURL" width="200" height="200"></iframe>
</body>
</html>

This works fine, and in options you can save anything you put into the url field. Now I want to get that saved value and make it be the src (myURL) for the iframe in popup.html

Example: So in options if you entered and saved http://www.google.com then in the popup.html the iframe would be:

<iframe src="http://www.google.com" id="myURL" name="myURL" width="200" height="200"></iframe>

Any help is appreciated.


Solution

  • Basic question, but there you go.

    1. Obviously, to do this you need JavaScript code. Chrome's Content Security Policy forbids inline code, so the code must go into a separate .js file (say, popup.js) and included in the HTML:

       <html>
         <head>
           <script src="popup.js"></script>
         </head>
         <body>
           <iframe id="myURL" name="myURL" width="200" height="200"></iframe>
         </body>
       </html>
      
    2. The code should:

    a. Read the value from localStroage

    b. Find the element on the page

    c. Assign its src property.

        // Read the value
        var url = localStorage.url;
          // or = localStorage["url"];
          // or = localStorage.get("url");
        
        // Find the element  
        var element = document.getElementById("myUrl");
    
        // Assign the property
        element.src = url;
         // or .setAttribute("src", url);
    

    Of course, all of this can be compressed in a single line of code by removing the temp variables url and element (see below).

    1. There is a problem with this, however. The code will execute when the <script> element is read - before the #myURL element is read. Therefore, it will fail, as element will not be found and will be undefined.

    There are two ways to fix it:

    a. Move the <script> tag below the element it refers to, like you did in options.html

    b. Wrap your code in a listener for an event that page is fully parsed and ready for it. I prefer this solution.

        document.addEventListener("DOMContentLoaded", function() {
          document.getElementById("myUrl").src = localStorage.url;
        });
    

    Further reading: