Last active
August 29, 2015 14:28
-
-
Save Infocatcher/2d001a8c72eb278c3686 to your computer and use it in GitHub Desktop.
Base64 converter for Gecko-based browsers, accepts any valid URL string
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
// https://gist.github.com/Infocatcher/2d001a8c72eb278c3686 | |
// Based on code from Custom Buttons extension | |
// https://addons.mozilla.org/files/browse/261190/file/components/CustomButtonsService.js#L210 | |
function ImageConverter(imageURL, feedback) { | |
this.imageURL = imageURL; | |
this.feedback = feedback; | |
this.bytes = []; | |
this.channel = Services.io.newChannel(imageURL, null, null); | |
this.channel.notificationCallbacks = this; | |
this.channel.asyncOpen(this, null); | |
} | |
ImageConverter.prototype = { | |
// nsISupports | |
QueryInterface: function(iid) { | |
if( | |
!iid.equals(Components.interfaces.nsISupports) | |
&& !iid.equals(Components.interfaces.nsIInterfaceRequestor) | |
&& !iid.equals(Components.interfaces.nsIRequestObserver) | |
&& !iid.equals(Components.interfaces.nsIStreamListener) | |
&& !iid.equals(Components.interfaces.nsIProgressEventSink) | |
) | |
throw Components.results.NS_ERROR_NO_INTERFACE; | |
return this; | |
}, | |
// nsIInterfaceRequestor | |
getInterface: function(iid) { | |
return this.QueryInterface(iid); | |
}, | |
// nsIRequestObserver | |
onStartRequest: function(aRequest, aContext) { | |
this.stream = Components.classes["@mozilla.org/binaryinputstream;1"] | |
.createInstance(Components.interfaces.nsIBinaryInputStream); | |
}, | |
onStopRequest: function(aRequest, aContext, aStatusCode) { | |
var contentType = this.channel.contentType; | |
//var data = String.fromCharCode.apply(null, this.bytes); | |
var data = this.bytes.map(function(code) { | |
return String.fromCharCode(code); | |
}).join(""); | |
this.channel = null; | |
var dataURI = "data:" + contentType + ";base64," + btoa(data); | |
this.feedback && this.feedback(dataURI); | |
}, | |
// nsIStreamListener | |
onDataAvailable: function(aRequest, aContext, aInputStream, aOffset, aCount) { | |
this.stream.setInputStream(aInputStream); | |
var chunk = this.stream.readByteArray(aCount); | |
this.bytes = this.bytes.concat(chunk); | |
}, | |
// nsIProgressEventSink | |
onProgress: function(aRequest, aContext, progress, progressMax) {}, | |
onStatus: function(aRequest, aContext, status, statusArg) {} | |
}; | |
// Usage example: | |
new ImageConverter("file://c:/autoexec.bat", function(dataURI) { | |
gBrowser.selectedTab = gBrowser.addTab(dataURI); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment