简体   繁体   中英

Getting a data URI for cross-domain content?

For all intents and purposes, let's say I have a webpage with an input field where users can enter an image URL, click a button, and be given a data URI for the resource at the other end of their URL (eg, the Google logo).

Reading around, I learned that you can get data URIs for images like so:

function imageToDataURI(src,callback)
{
    var canvas = document.createElement('canvas'),
        img    = document.createElement('img');

    img.onload = 
        function()
        {
            canvas.width  = img.width;
            canvas.height = img.height;
            canvas.getContext('2d').drawImage(img, 0, 0);
            callback(canvas.toDataURL());
        };
    img.src = src;
}

However, a lot of people (myself included) are getting "SECURITY_ERR: DOM Exception 18" because canvas elements get tainted when cross-domain images are drawn on them and tainted canvases return the above error on canvas.toDataURL() (see Why does canvas.toDataURL() throw a security exception? ). My problem is: I really need to support cross-domain URLs!

What can I do?

I read about a bunch of available options for getting cross-domain data here . There are pretty much 3 categories of solutions:

  1. those that create huge security holes in your webpage
  2. those that don't but require controlling the cross-domain server
  3. those that require you to turn your own server into a proxy

If you can't afford #1, are not in #2, and have a node.js server at your disposal, here's a super-simple, plug-and-play node.js module that'll do #3.

/* return a datauri encoding of the resource at the given url */
exports.dataurize = 
    function(url,callback)
    {
        var request = 
            require('http').request(
                {'host':url.host || 'localhost', 
                 'port':url.port || 80, 
                 'path':url.path || '/'},
                function(resp)
                {
                    var data = '';
                    resp.setEncoding('binary');
                    resp.on('data', function(chunk) {data += chunk;});
                    resp.on('end',
                        function()
                        {
                            if( resp.statusCode == 200 )
                                callback(
                                    undefined,
                                    'data:'+resp.headers['content-type']+';base64,'+
                                       new Buffer(data,'binary').toString('base64'));
                            else
                                callback({'statusCode':resp.statusCode, 'reason':data});
                        });
                });
        request.on('error',
            function(err)
            {
                callback({'statusCode':0, 'reason':err});
            });

        request.end();
    };

Integrate it into your backend and you're home free for #3. Circling back to the original problem, imageToDataURI() now queries your node.js backend with a url, and your backend responds with the result of

require('./dataurize').dataurize(...) 

ie, with the desired dataURI.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM