Created
June 29, 2016 22:59
-
-
Save akirattii/4fefca3a45bf2c4015ef71fc6413c87a to your computer and use it in GitHub Desktop.
Downloads and views an image on Chrome App and Extension
This file contains 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
/** | |
* 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