Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch CORS error

I'm trying to load a CORS-disabled image, and get the error:

Cross-origin image load denied by Cross-Origin Resource Sharing policy.

I've tried catching the error as follows, but that obviously will not work.

How can I catch CORS errors after setting the .src property of an image?

like image 807
Randomblue Avatar asked Dec 27 '25 16:12

Randomblue


1 Answers

Use the onError event.

if(image.addEventListener) {
    image.addEventListener('error', function (e) {
        e.preventDefault(); // Prevent error from getting thrown
        // Handle error here
    });
} else {
    // Old IE uses .attachEvent instead
    image.attachEvent('onerror', function (e) {
        // Handle error here
        return false; // Prevent propagation
    });
}

Code should probably be consolidated so you don't have to write your code twice, but hopefully you've got the idea.

like image 68
LoveAndCoding Avatar answered Dec 30 '25 04:12

LoveAndCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!