【问题标题】:Using localStorage base64 image in chrome content script [duplicate]在 chrome 内容脚本中使用 localStorage base64 图像 [重复]
【发布时间】:2014-07-27 00:01:10
【问题描述】:

我正在尝试使用我放入 localStorage 的图像作为我的 chrome 扩展中的 base64 字符串,以此为指导: How to save an image to localStorage and display it on the next page? 我将图像作为可选文件存储在我的 options.js 中,并且它在会话之间的选项页面上持久存在。但在我的主 Script.js 中,相同的键始终为空。这给了我选项页面上的完整字符串,但是当我在我的主脚本中运行相同的代码时,在其他所有页面上都为空:

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

本地存储有什么我不明白的地方吗?

【问题讨论】:

  • 错过了那个。谢谢!

标签: google-chrome-extension local-storage


【解决方案1】:

**将图像保存为 Base64。然后我将 Base64 字符串保存为我的 localStorage 值。

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

获取图片的Javascript代码:

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

Img= document.getElementById('newImage');

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

【讨论】:

  • 谢谢,但我在显示图像时没有问题。问题是 var Image = localStorage.getItem('imgSaved') 总是在我保存它的选项页面以外的任何页面上返回 null 。我可以让图像在那里显示,但本地存储不记得任何其他页面上的密钥。
  • 你可以在一个通用的js(外部js)中编写上面的代码,并在两个页面或你想使用它的页面上给出那个js的链接
猜你喜欢
  • 2011-04-25
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
相关资源
最近更新 更多