且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

访问控制 - 允许 - 来源'错误不允许捕捉'源

更新时间:2022-12-07 23:26:41

正如@TamasHegedus评论,图像仍然可以加载CORS错误,但它不允许操作图像数据。这意味着您可以使用画布来尝试操纵图像并捕获任何抛出的错误。



这种技术适用于画布支持的图像。如果您想使用 answer ,请参阅 @Kaiido https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/img#attr-crossoriginrel =nofollow noreferrer> 图片#crossOrigin 属性。他的解决方案还检测该属性是否受支持,并在必要时使用画布。

  //必须在IE9 +中工作。 

var img = new图片;

img.onload = function(){

var canvas = document.createElement('canvas');

//调整画布大小,否则img不会被渲染
canvas.width = img.width;
canvas.height = img.height;

//获取画布渲染上下文2d
var ctx = canvas.getContext('2d');

//首先绘制图像
ctx.drawImage(img,0,0);

尝试{
/ *获得第一个像素* /
ctx.getImageData(0,0,1,1);

/ *没有错误捕获 - 没有cors错误* /
alert(跨域访问可用。);

} catch(e){
alert(跨域访问被阻止);
}
};

img.src ='https://i.stack.imgur.com/Kt3vI.png?s=48&g=1';


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?

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.

// Must work in IE9+.

var img = new Image;

img.onload = function() {

    var canvas = document.createElement('canvas');

    // resize the canvas, else img won't be rendered
    canvas.width = img.width;
    canvas.height = img.height;

    // get the canvas rendering context 2d
    var ctx = canvas.getContext('2d');

    // draw the image first
    ctx.drawImage(img, 0, 0);

    try {
        /* get first pixel */
        ctx.getImageData(0, 0, 1, 1);

        /* no error catched – no cors error */
        alert("Cross-domain access available.");

    } catch (e) {
        alert("Cross-domain access blocked.");
    }
};

img.src = 'https://i.stack.imgur.com/Kt3vI.png?s=48&g=1';