1

I am trying to build an extension that will allow users to put some parameters into a text box in the popup, generate a link using that information and add it to the said popup. I have all that working, but needless to say, it gets flushed every time the user opens the extension anew. I'd like the info that has been put in there to stay, but can't seem to get it to work. Here's what I have thus far:

manifest.json

{
  "manifest_version": 2,
  "name": "Test",
  "description": "Test Extension",
  "version": "1.0",

  "permissions": [
    "http://*/*", 
    "https://*/*"
  ],

  "browser_action": {
    "default_title": "This is a test",
    "default_popup": "popup.html"
  }
}

popup.html

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="linkContainer"/>
<input type="text" id="catsList"/>
<button type="button" id="addToList">Add</button>
<script src="popup.js"></script>
</body>
</html>

popup.js

function addCats() 
{
    var a = document.createElement('a');
    a.appendChild(document.createTextNode(document.getElementById('catsList').value));
    a.setAttribute('href', 'http://google.com');
    var p = document.createElement('p');
    p.appendChild(a)
    document.getElementById('linkContainer').appendChild(p);
    indexLinks()
}

function indexLinks() 
{
    var links = document.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) 
    {
        (function () 
        {
            var ln = links[i];
            var location = ln.href;
            ln.onclick = function () 
            {
                chrome.tabs.create({active: true, url: location});
            };
        })();
    }
};

document.getElementById('addToList').onclick = addCats;

My guess is that I need something along the lines of

localStorage['cointainer'] = document.getElementById('linkContainer');

at the end of addCats() and a call to something like

function loadLocalStorage()
{
    var container = document.getElementById('linkContainer');
    container.innerHTML = localStorage['container'];
}

at the beginning, but doing that didn't work. Not sure what's going wrong.

Also,if there is a different way to save users' additions, I'd be open to them.

Minas Abovyan
  • 671
  • 1
  • 6
  • 15

1 Answers1

0

localStorage only supports storing string values. You can't store entire HMTL elements.

localStorage['foo'] = 'bar';
localStorage['foo'] = JSON.stringify({'bar': 'baz'});
localStorage['foo'] = JSON.stringify(['bar', 'baz', 'qux']);

You will have to iterate over the list of elements you want to save, put string value into an array, and JSON.stringify before saving it to localStorage. Then on load you pull the value out of localStorage, JSON.parse it, and create new HTML elements for each value in the array.

abraham
  • 46,583
  • 10
  • 100
  • 152
  • Thank you! Worked perfectly. My links are no longer working and I don't know why, but the information is being stored, which is great. – Minas Abovyan May 31 '14 at 12:52