Skip to content

Instantly share code, notes, and snippets.

@akirattii
Created June 29, 2016 22:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akirattii/4fefca3a45bf2c4015ef71fc6413c87a to your computer and use it in GitHub Desktop.
Save akirattii/4fefca3a45bf2c4015ef71fc6413c87a to your computer and use it in GitHub Desktop.
Downloads and views an image on Chrome App and Extension
/**
* dl an external image resource and append it as an img element into the rootEl
*
* @param {String}
* image resource's url
* @param {Element} Optional
* root element to be appended an img element.
* @param {Function} Optional
* callback function. 'function(imgEl){...}'
*/
function loadImage(url, rootEl, cb) {
if (!url) {
console.error("url is required.");
return cb && cb(null);
}
if (!rootEl) rootEl = document.body;
let xhr = new XMLHttpRequest();
xhr.onload = function(e) {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
let img = document.createElement('img');
rootEl.appendChild(img);
img.src = window.URL.createObjectURL(this.response);
return cb && cb(img);
}
}
};
xhr.responseType = "blob";
xhr.open('GET', url, true);
xhr.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment