Chrome高版本浏览器img通过src获取图片失败

本文总结了解决Chrome高版本浏览器中img标签通过src属性跨域获取图片失败的几种方法,包括更改浏览器设置、添加crossOrigin属性、设置Referrer-Policy等。在分析了不同版本Chrome的行为和错误提示后,找到了成功解决该问题的方案。

解决方案总结:

1、打开新网页,浏览器输入:​​chrome://flags/#block-insecure-private-network-requests,改成Disabled,重启浏览器。(需要客户手动操作,不采纳)

2、给img添加crossOrigin 属性(此方法不好用,can i use显示浏览器不支持img 标签的 src跨域问题

3、<meta name="referrer" content="no-referrer-when-downgrade" /> 参考:change referrer-policy in react js(未采用不适合项目)

4、前端设置方法( 参考HTTP请求之referrer与Referrer-Policy
       ① 通过Referrer-Policy HTTP header设置:Referrer-Policy: origin

        ②通过<meta>元素改变Referrer Policy,直接修改名为referrer的内容

  <meta name="referrer" content="origin">

        ③ 给 <a> <area><img><iframe> 或<link>元素设置referrerpolicy属性

  <a href="http://example.com" referrerpolicy="origin">

        ④ 如需设置不显示referrer信息,可以给 <a><area> <link>元素设置rel的链接关系。

  <a href="http://example.com" rel="noreferrer">


react,img标签src获取图片提示跨域,

<img src={originSrc[i]} key={i} />

控制台提示:

Access to image at 'http://127.0.0.1:15284/C:/Users/28929/camera_0.jpg?1655275037147' from origin 'http://171.5.37.13' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`.
Access to image at 'http://127.0.0.1:15284/C:/Users/28929/camera_1.jpg?1655275037147' from origin 'http://171.5.37.13' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`.

分析:

1、谷歌94版本上基本上端口号4位成功,5位失败,此时误以为是端口5位数导致(端口随机生成),但随着操作次数增多发现,4位端口号也会失败,如下:

Access to image at 'http://127.0.0.1:1042/C:/Users/28929/camera_0.jpg?1655279684455' from origin 'http://171.5.37.13' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space `local`.

 2、谷歌84版本,4、5位端口号都获取图片成功,查看资料得知Chrome 新的默认 Referrer-Policy : strict-origin-when-cross-origin

 3、后来又看到一篇文章:HTTP请求之referrer与Referrer-Policy ,对比成功和失败发现

    失败:

General
	Request URL: http://127.0.0.1:23246/C:/Users/28929/camera_0.jpg?1655279684455
	Referrer Policy: strict-origin-when-cross-origin
Response Headers
	Referer: http://171.5.37.13/
	...

成功:

General
	Request URL: http://127.0.0.1:23382/C:/Users/28929/camera_0.jpg?1655280203114
	Request Method: GET
	Status Code: 200 OK
	Remote Address: 127.0.0.1:23382
	Referrer Policy: strict-origin-when-cross-origin
Response Headers
	...
	Accept: image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8
	Accept-Encoding: gzip, deflate, br
	Accept-Language: zh-CN,zh;q=0.9
	Connection: keep-alive
	Host: 127.0.0.1:23382
	Referer: http://172.27.1.144/
	...

试了一把,诶?

<img src={originSrc[i]} referrerpolicy='origin' key={i} />

好像靠谱,至此问题终于解决。

总结写在文章最开头,方便大家快速找到解决方案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值