javascript - 捕获 CORS 错误

标签 javascript cors

我正在尝试加载已禁用 CORS 的图像,但出现错误:

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

我已经 try catch 错误 as follows ,但这显然行不通。

如何在设置图像的 .src 属性后捕获 CORS 错误?

最佳答案

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
    });
}

代码可能应该合并,这样您就不必编写两次代码,但希望您已经明白了。

关于javascript - 捕获 CORS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13103076/

相关文章:

javascript - VueJS 调度函数的执行顺序导致问题

javascript - Sencha 触摸 : Problem loading form: Cannot read property "OffsetBoundary of undefined"

javascript - 如何在滚动上为 div 设置动画?

javascript - CORS 预检错误 redux & loopback API

javascript - 当来源为 http 且目标 url 为 https 时,如何在本地网络中发出 POST 请求?

Clojure ring-cors/wrap-cors 设置

javascript - 为什么 Node.js 有 1.76 Gb 的内存限制?

javascript - 正确使用Physics.aabb.union()

php - 访问控制允许来源 angularjs 到 php

ajax - 支持 CORS 的服务器?