Randomblue
Randomblue

Reputation: 116263

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?

Upvotes: 3

Views: 2809

Answers (1)

LoveAndCoding
LoveAndCoding

Reputation: 7947

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.

Upvotes: 5

Related Questions