Chrome扩展程序 - 将外部照片加载到IMG中 - 避免混合内容

chrome extension - load an external photo into an img - avoiding mixed content

本文关键字:混合 IMG 加载 程序 扩展 外部 Chrome 照片      更新时间:2023-09-26

我正在编写一个chrome扩展(内容脚本),它从api获取一些照片网址并将其显示在当前页面上的某个位置。

问题是有时照片网址是http(指向网站上托管的照片,而不是来自我的服务器),但当前页面是https,这会导致混合内容错误。

因此,我尝试使用背景脚本.js从我的内容脚本向其发送消息以下载图像。

我尝试了两种方法在后台下载和存储图像.js -

function getImageDataURL(url, callback) {
  var data, canvas, ctx;
  var img = new Image();
  img.setAttribute('crossOrigin', 'anonymous');
  img.onload = function () {
    canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    callback(canvas.toDataURL());
  };
  img.src = url;
}

由于以下原因而失败:

来自源"http://www.not-my-server.com"的图像已被阻止 按跨域资源共享策略加载:否 "访问控制允许源"标头存在于请求的上 资源。原产地"铬 extension://..."因此不允许 访问。

以及:

  jQuery.ajax({
    url: url,
    //data: myData,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    success: function() { callback(false) },
    error: function() { callback(true) }
  });

由于以下原因而失败:

拒绝加载脚本"http://www.not-my-server.com/..."因为 它违反了以下内容安全策略指令: "script-src 'self' https://*.my-server.com https://localhost:4443/"。

我应该以某种方式更改我的chrome扩展程序的CSP以包含所有图像吗?还有其他方法可以做到这一点吗?我想要的只是在后台临时下载一个jpg,并在内容脚本html中使用它。

谢谢。

(这不是这个问题的正确解决方案,但现在它解决了我的痛苦)

通过使用第三方SSL代理服务可以完全避免此问题,该服务适用于图像:https://images.weserv.nl/

var url = "http://some-website.com";
var secured_url;
if (url.indexOf("https://") == 0) {
    secured_url = url;
} else {
    // remove the protocol from the passed-in url
    secured_url = "//images.weserv.nl/?url=" + url.substring(7) + "&h=60&w=60";
}