访问控制 - 允许 - 来源'错误不允许捕捉'源 [英] Catching 'Origin is not allowed by Access-Control-Allow-Origin' error

查看:159
本文介绍了访问控制 - 允许 - 来源'错误不允许捕捉'源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  img = new Image(); 

img.crossOrigin =anonymous;

尝试{
cimg.src = document.getElementById(url).value;
}
catch(err){
alert(无法访问image.Cross-Domain访问被阻止);
};

所以,我想检测/捕获跨域访问被阻止的错误。

经过一番思考,我发现它的src加载是异步&因此抓块不会工作。有没有什么办法来检测错误,所以我可以有效地处理它?<​​/ p>

解决方案

正如@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';

这篇关于访问控制 - 允许 - 来源'错误不允许捕捉'源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆