0

I'm writing a chrome extension (content script) that gets some photo url from an api and shows it in some place on the current page.

The problem is that sometimes the photo url is http (to a photo hosted on a website, not from my server), but the current page is https, which leads to mixed-content errors.

So, I've tried using a background.js script, sending it a message from my content-script to download the image.

I've tried two methods to download and store the image in background.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;
}

which fails due to:

Image from origin 'http://www.not-my-server.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://...' is therefore not allowed access.

and also:

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

Which failed due to:

Refused to load the script 'http://www.not-my-server.com/...' because it violates the following Content Security Policy directive: "script-src 'self' https://*.my-server.com https://localhost:4443/".

Should I change my chrome-extension's CSP to include all images somehow? Is there some other way to do it? All I want is to simply temporarily download a jpg in the background, and use it in the content-script html.

Thanks.

marmor
  • 27,641
  • 11
  • 107
  • 150
  • This is not a duplicate of http://stackoverflow.com/questions/22165414/access-to-image-and-video-data-from-browser-extension-vs-cors since the url of the image src is not known in advance, it is received by an api call, so I can't add the src urls to the manifest – marmor Jul 13 '16 at 14:51

1 Answers1

1

(This is not a proper solution for the question, but for now it solves my pain)

This issue can be averted altogether by using a 3rd-party ssl proxy service, this one works well for images: 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";
}
marmor
  • 27,641
  • 11
  • 107
  • 150