0

I'm trying to use an image that I put into localStorage as a base64 string in my chrome extension, using this as a guide: How to save an image to localStorage and display it on the next page? I store the image as a selectable file in my options.js, and it's persistent on the options page from session to session. But in my main Script.js, that same key is always null. This gives me the full string on my options page, but is null on every other page when I run the same code in my main script:

var dataImage = localStorage.getItem('imgData');
console.log(dataImage);

Is there something about local storage I'm not understanding?

Community
  • 1
  • 1

1 Answers1

1

**Save the image as a Base64. Then I save the Base64 string as my localStorage value.

img1= document.getElementById('imgid');

imgResult= convertoBase64Image(img1);

localStorage.setItem("imgSaved", imgResult);

Here is the function that converts the image to a Base64 sting:

function convertoBase64Image(img) {

  // Create an empty canvas element
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;

  // Copy the image contents to the canvas
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);

  // Get the data-URL formatted image
  // Firefox supports PNG and JPEG. You could check img.src to guess the
  // original format, but be aware the using "image/jpg" will re-encode the image.
  var dataURL = canvas.toDataURL("image/png");
  return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

new image.src =""
<img src="" id="newImage" />

Javascript code to retrieve image:

var Image = localStorage.getItem('imgSaved');

Img= document.getElementById('newImage');

Img.src = "data:image/png;base64," + Image ;
Janx
  • 3,285
  • 3
  • 19
  • 24
Gaurav
  • 11
  • 2
  • thanks, but I don't have a problem displaying the image. The problem is that var Image = localStorage.getItem('imgSaved') always returns null on any page other than the options page where I saved it. I can get the image to display there, but local storage is not remembering the key on any other pages. – user3700697 Jul 26 '14 at 15:54
  • you can write above code in a common js(external js) and give link of that js on both pages or on page you want to use it – Gaurav Jul 27 '14 at 15:50