Search code examples
javascriptfirefoxfirefox-addoncross-domainfirefox-addon-sdk

Load image using crossOrigin attr. in Firefox addon sdk


In content script in Firefox addon SDK I'm loading image like this way:

var img = new Image();
img.crossOrigin = "Anonymous";
img.src = URL;
img.onload = function (data) {
    var canvas = document.createElement("canvas");
    canvas.width =this.width;
    canvas.height =this.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(this, 0, 0);
    var dataURL = canvas.toDataURL("image/jpeg");
    callback.call(this,dataURL);
}

The request has been done but the response header is empty body, I think the problem in cross origin because it loaded successfully from page allow cross origin.

How can I solve this inside content script? I need the image data to store it in local storage.

Regards, Mohammad.


Solution

  • Finally the problem has been solved, thank you guys for a great discussion. How I solved it:

    The problem was a cross origin problem as @the8472 mentioned, so what I did is making the request using SDK for the image and convert its data to base64 based on this answer.

    The request usign SDK like this:

    var Request = require("sdk/request").Request;
    Request({
                url: imageURL,
                overrideMimeType:"text/plain; charset=x-user-defined",
                onComplete: function(imageData) {
                      var imageData = "data:image/jpeg;base64,"+base64Encode(imageData.text);
                      console.log(imageData);
                }
            }).get();
    

    The function of base64Encode which I used from the previous answer is:

    function base64Encode(str) {
    var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    var out = "", i = 0, len = str.length, c1, c2, c3;
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt((c1 & 0x3) << 4);
            out += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            out += CHARS.charAt(c1 >> 2);
            out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
            out += CHARS.charAt((c2 & 0xF) << 2);
            out += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        out += CHARS.charAt(c1 >> 2);
        out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        out += CHARS.charAt(c3 & 0x3F);
    }
    return out;
    }
    

    Then I save the result in local storage.

    Thank you all :)