为什么要做这个东西
最近做一个需求,前端请求一个接口,后台生成文件以后返回文件名,前端再通过window.open下载这个文件。发现window.open有时生效有时不生效,后来查阅资料后发现浏览器出安全方面的考量,会把用户操作完页面后一段时间内的window.open视为非法操作屏蔽掉,这个时间后来经过测试大概是五秒;如果接口请求比较耗时就会导致open被屏蔽。这里封装一个函数,用户操作完页面4.5秒后请求没有完成时先执行window.open,接口请求完成后替换新窗口的url完成文件下载。如果在4.5秒内请求完成了就直接执行window.open
代码
function asyncOpenWindow(promise) {
let newWindow = null;
const timeOut = setTimeout(() => {
try {
if (navigator.userAgent.indexOf('Chrome') > -1) {
newWindow = window.open('', '', 'width=500,height=100,location=no,menubar=no');
}
} catch (e) {
console.log(e);
}
}, 4500);
promise.then((url) => {
clearTimeout(timeOut);
if (newWindow) {
newWindow.location.href = url;
} else {
window.open(url);
}
});
}
使用
const fn =asncy function(){
const url =await requset
return url
}
asyncOpenWindow(fn())