Canvas tainted by cross-origin data

后端 未结 4 1700
南笙
南笙 2020-11-27 19:05

I\'m loading a motion jpeg from third-party site, which I can trust. I\'m trying to getImageData() but the browser (Chrome 23.0) complains that:



        
4条回答
  •  情深已故
    2020-11-27 19:44

    While the question is very old the problem remains and there is little on the web to solve it. I came up with a solution I want to share:

    You can use the image (or video) without the crossorigin attribute set first and test if you can get a HEAD request thru to the same resource via AJAX. If that fails, you cannot use the resource. if it succeeds you can add the attribute and re-set the source of the image/video with a timestamp attached which reloads it.

    This workaround allows you to show your resource to the user and simply hide some functions if CORS is not supported.

    HTML:

    
    

    JavaScript:

    var target = $("#testImage")[0];
        currentSrcUrl = target.src.split("_t=").join("_t=1"); // add a leading 1 to the ts
    $.ajax({
        url: currentSrcUrl,
        type:'HEAD',
        withCredentials: true
    })
    .done(function() {
        // things worked out, we can add the CORS attribute and reset the source
        target.crossOrigin = "anonymous";
        target.src = currentSrcUrl;
        console.warn("Download enabled - CORS Headers present or not required");
        /* show make-image-out-of-canvas-functions here */
    })
    .fail(function() {
        console.warn("Download disabled - CORS Headers missing");
        /* ... or hide make-image-out-of-canvas-functions here */
    });
    

    Tested and working in IE10+11 and current Chrome 31, FF25, Safari 6 (Desktop). In IE10 and FF you might encounter a problem if and only if you try to access http-files from a https-script. I don't know about a workaround for that yet.

    UPDATE Jan 2014:

    The required CORS headers for this should be as follows (Apache config syntax):

    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Headers "referer, range, accept-encoding, x-requested-with"
    

    the x-header is required for the ajax request only. It's not used by all but by most browsers as far as I can tell

提交回复
热议问题