Skip to content

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

As @TamasHegedus commented, the image can still be loaded with the CORS error, but it doesn’t allow the image data to be manipulated. That means you can use the canvas to try to manipulate the image and catch any thrown errors.

This technique would work for canvas-supported images. See @Kaiido‘s answer if you want a simpler alternative using the Image#crossOrigin property. His solution also detects whether the property is supported and uses canvas when necessary.

// Must work in IE9+.

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 {
        /* get first pixel */
        ctx.getImageData(0, 0, 1, 1);

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

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

img.src = 'https://i.stack.imgur.com/Kt3vI.png?s=48&g=1';