Debanjan Dhar Debanjan Dhar - 1 year ago 55
HTML Question

Catching 'Origin is not allowed by Access-Control-Allow-Origin' error

img = new Image();

img.crossOrigin = "anonymous";

try {
cimg.src = document.getElementById("url").value;
catch(err) {
alert("Cannot access image.Cross-Domain access blocked");

So, i want to detect/catch Cross-Domain access blocked error.

After some thought i found out that it src loading is async & thus the catch block wont work. Is there any way to detect the error so i can handle it efficiently?

Answer Source

Basically, as the @TamasHegedus commented, the image can still be loaded with the cors error, but it doesn't allow to get its data to be manipulated. That means you can use the canvas to try to manipulate the image, cause you can render it.

You can't directly catch the cors error. If you use the CanvasRenderingContext2D().getImageData you'll get the cors error, so you can catch it. Then, there's a way to catch the cors error using the canvas element to draw the image on, then get its data.

This technique would work for images, but XMLHttpRequest works for other contents.

var img = new Image;

img.onload = function() {

    var canvas = document.createElement('canvas');

    // resize the canvas, else img won't be rendered
    canvas.width = img.width;
    canvas.height = img.height;

    // get the canvas rendering context 2d
    var ctx = canvas.getContext('2d');

    // draw the image first
    ctx.drawImage(img, 0, 0);

    try {
        /* try to get image data */
        ctx.getImageData(0, 0, img.width, img.height);

        /* no error catched – no cors error */
        alert("Cross-domain access available.");

    } catch (e) {
        alert("Cross-domain access blocked.");

img.src = '';