Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

img 标签src赋值实现跨域请求,部分请求在部分移动端浏览器中,无法发出正确的请求

背景
实现一个第三方上报的组件,get请求,因为跨域,考虑两种方式实现

  1. 给img的src赋值请求链接
  2. jsonp,创建script标签,给src属性赋值请求链接

问题描述
测试发现,在PC端,基本没有问题,跨域请求均能正常请求且返回,抓包结果是这样的
image.png

在移动端,ios 微信浏览器中无法发出请求,抓包结果是这样的
image.png

安卓微信浏览器中正常请求,qq浏览器中无法请求

这是img的src实现的代码

const handlerReportRequest =?(requestUrl) => {

 if (!requestUrl) return false;

 try {

 let img = new Image();

 img.onload = img.onerror =?() => {

 img.style.display = 'none'

 document.body.removeChild(img);

 img = null;

 };

 img.src = requestUrl;

 document.body.appendChild(img);

 } catch (e)?{

 console.warn(e)

 }

};

jsonp方式的实现代码

const jsonp =?({ requestUrl, callbackName }) => {

 return new Promise((resolve, reject) => {

 //?初始化回调函数名称

 callbackName =

 callbackName || "cb" + Math.random().toString().replace(".", "");

 let scriptEle = document.createElement("script");

 scriptEle.src = requestUrl;

 document.body.appendChild(scriptEle);

 //?绑定到?window?上,为了后面调用

 window[callbackName]?= data => {

 resolve(data);

 document.body.removeChild(scriptEle);

 };

 });

};

const callbackName =??(data) => {

 console.log(data)

}

问题是这段代码,对于有些跨域请求,在任何端都是没有发现问题的,但是对另外一些跨域请求,在失败的情况下,抓包发现就只能看到请求了http的域名,没有请求完全的https的get请求

测试demo
图片上报方式:
https://bunnymelody.github.io...
jsonp上报方式:
https://bunnymelody.github.io...

尝试过以下方式

  1. 检查请求链接的长度,但那些可以支持跨域请求的链接,这个长度也是可以正常请求的
  2. 给img赋值anoymous属性,在chrome会报跨域错误
  3. 打印img的onerror事件,报错isTrusted: true,但这个报错在pc的chrome浏览器中也会报
  4. 针对失败的链接,在chrome使用第三方在线平台发起get请求,请求正常返回
  5. 直接把在html中新建image标签,将src属性赋值为请求的链接,请求也不能正常发出

所以,img和jsonp发起跨域请求,在移动端浏览器中可能失败的原因是怎样的呢,如果跟第三方接口有关,具体是什么有关呢?

因为目前问题发生在 移动端 部分请求 部分浏览器中,这可能跟浏览器的什么策略相关吗

或者在不需要第三方配合 设置 Access-Control-Allow-Origin的情况话,单纯从前端的角度,如何实现上报请求的跨域呢


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...