Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
fetch image resources : works well with chrome extension
FetchImageAsBlob('', function(err, img) {
if (err) {
// play with img
function FetchImageAsBlob(url, cb) {
var req = createCORSRequest('GET', url);
req.onload = function() {
var img = new Image();
img.onload = function() {
cb(null, img);
img.src = URL.createObjectURL(req.response);
req.onerror = function(e) {
req.responseType = 'blob';
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects., url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
return xhr;

This comment has been minimized.

Copy link

@juanlatorre juanlatorre commented Sep 28, 2018

Hey man, I'm trying to make this work but it throws error:
Refused to connect to '' because it violates the following Content Security Policy directive: "default-src 'self' 'unsafe-eval'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment