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?
In browsers supporting crossOrigin requests, (which should be preferred ones), if you set the
crossOrigin
to'anonymous'
, and try to set your element'ssrc
pointing to a file hosted on a improperly set-up server, theload
event won't fire, and instead, anerror
event will.It is important to understand that in the case of a failed crossOrigin request, the server will answer directly that it doesn't accept the request, so only headers are sent between your user and the distant server, while doing the other way around (first try without the crossOrigin request, then try with), you have to first download entirely* the resource , then download it again with the crossOrigin attribute set...
Same applies for audio, video, and xhr requests.
So one should first set the crossOrigin of cross-origin requests, then if it fails it means that the other hand is not properly configured.
-* Actually, only images need to be downloaded entirely, all other resources can be tested before the end.
Ps : in case of same-origin request, the crossOrigin attribute should not hurt, so this check can still be performed.
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.