Skip to content

Instantly share code, notes, and snippets.

@cvializ
Created May 11, 2016 23:31
Show Gist options
  • Save cvializ/a0c21c594e7b9b974d2bd99c9a827b5a to your computer and use it in GitHub Desktop.
Save cvializ/a0c21c594e7b9b974d2bd99c9a827b5a to your computer and use it in GitHub Desktop.
Loading images from the background page of a browser extension.
/* A map of functions listening for messages from the content scripts */
var listeners = {
/* ... */
load_image: function (path, respond, tab) {
// The Firefox worker XHR dislikes protocol-less URLs, so prefix with the tab's protocol.
path = (path.indexOf('//') === 0 ? tab.url.slice(0, tab.url.indexOf(':') + 1) + path : path);
var imageType = path.slice(path.lastIndexOf('.') + 1);
var xhr = new XMLHttpRequest();
xhr.open('GET', path, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
if (this.status === 200 || this.status === 0) {
respond({ uri: 'data:image/' + imageType + ';base64,' + arrayBufferToBase64(this.response) });
} else {
respond({ error: 'Status ' + this.status + ' did not equal 200 for ' + path });
}
};
xhr.onerror = respond.bind(null, { error: 'Couldn\'t load image ' + path });
xhr.send();
},
/* ... */
};
// A good, well-supported way to get base64 out of bytes
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment