0

I am trying to retrieve an SVG image, store it locally, and use it later in the popup.js. The retrieval is done by a content script:

   var svg = document.getElementById("svg");
        chrome.storage.local.set({'svg': svg}, function() {
            console.log(svg.localName === "svg"); //returns true
        });

Unfortunately, the popup seems to get nothing but an empty object.

chrome.storage.local.get("svg", function(svg) {
                console.log(svg.localName === "svg"); //returns false
});

I have little to no experience with Javascript and Chrome extensions, so I am probably doing something very stupid here.

Felix
  • 369
  • 4
  • 15

1 Answers1

1

chrome.storage is for JSON-ifiable objects, not for the complex class instances like DOM elements. To inspect the storage use Storage Area Explorer extension.

In your case, store the outer HTML:

var svg = document.getElementById('svg');
chrome.storage.local.set({svg: svg.outerHTML});

Then recreate the element from the HTML:

chrome.storage.local.get('svg', data => {
    var tmp = document.createElement('div');
    tmp.innerHTML = data.svg;
    var svg = tmp.firstElementChild;
    document.body.appendChild(svg);
});

or

chrome.storage.local.get('svg', data => {
    document.body.insertAdjacentHTML('beforeend', data.svg);
});

Advanced tip: when storing a lot of HTML/text in chrome.storage, consider using LZstring.

Community
  • 1
  • 1
wOxxOm
  • 65,848
  • 11
  • 132
  • 136