Last active
September 28, 2018 18:13
-
-
Save darul75/385332713a3c1ce9bf1d to your computer and use it in GitHub Desktop.
fetch image resources : works well with chrome extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FetchImageAsBlob('https://gist.github.com/fluidicon.png', function(err, img) { | |
if (err) { | |
console.log(err); | |
return; | |
} | |
// play with img | |
}); | |
function FetchImageAsBlob(url, cb) { | |
var req = createCORSRequest('GET', url); | |
req.onload = function() { | |
var img = new Image(); | |
img.onload = function() { | |
URL.revokeObjectURL(this.src); | |
cb(null, img); | |
}; | |
img.src = URL.createObjectURL(req.response); | |
}; | |
req.onerror = function(e) { | |
cb(e); | |
}; | |
req.responseType = 'blob'; | |
req.send(); | |
} | |
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. | |
xhr.open(method, 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(); | |
xhr.open(method, url); | |
} else { | |
// Otherwise, CORS is not supported by the browser. | |
xhr = null; | |
} | |
return xhr; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey man, I'm trying to make this work but it throws error:
Refused to connect to 'https://gist.github.com/fluidicon.png' 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.