Skip to content
Advertisement

Catching ‘Origin is not allowed by Access-Control-Allow-Origin’ error

JavaScript

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?

Advertisement

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.

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement