Google chrome extension 在chrome内容脚本中使用localStorage base64映像

Google chrome extension 在chrome内容脚本中使用localStorage base64映像,google-chrome-extension,local-storage,Google Chrome Extension,Local Storage,我正在尝试使用一个图像,将其作为我的chrome扩展中的base64字符串放入localStorage,并以此作为指导: 我将图像作为可选文件存储在我的options.js中,并在不同会话的选项页面上保持不变。但是在我的main Script.js中,同一个键总是空的。这在我的选项页面上提供了完整的字符串,但当我在主脚本中运行相同的代码时,在其他页面上为空: var dataImage = localStorage.getItem('imgData'); console.log(dataImag

我正在尝试使用一个图像,将其作为我的chrome扩展中的base64字符串放入localStorage,并以此作为指导: 我将图像作为可选文件存储在我的options.js中,并在不同会话的选项页面上保持不变。但是在我的main Script.js中,同一个键总是空的。这在我的选项页面上提供了完整的字符串,但当我在主脚本中运行相同的代码时,在其他页面上为空:

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

本地存储有什么我不了解的吗?

**将映像另存为Base64。然后将Base64字符串保存为本地存储值

img1= document.getElementById('imgid');

imgResult= convertoBase64Image(img1);

localStorage.setItem("imgSaved", imgResult);
以下是将图像转换为Base64格式的函数:

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" />

谢谢,但是我在显示图像时没有问题。问题在于,var Image=localStorage.getItem('imgSaved')总是在我保存它的选项页面以外的任何页面上返回null。我可以让图像显示在那里,但是本地存储没有记住任何其他页面上的键。你可以在一个公共js(外部js)中编写上述代码,并在两个页面或你想使用它的页面上提供该js的链接。非常感谢。
var Image = localStorage.getItem('imgSaved');

Img= document.getElementById('newImage');

Img.src = "data:image/png;base64," + Image ;