异步处理后,弹出下载框被拦截

最近做文件传输功能,文件下载本想用window.open() 弹出新标签页浏览器自己下载,

但是下载之前需要对文件进行压缩处理后再返回下载地址,这样使用window.open()就被浏览器拦截了。

网上搜了很多,开始用隐藏的iframe下载,如果url地址无效,页面没有提示不友好。

用隐藏的a 标签,触发click()事件也被拦截。后来终于找到一个不被拦截的,a标签加download的属性不被拦截。

//下载    
function downloadUrl(url,name) {   
    var a = document.createElement('a');    
    a.setAttribute('href', url);  
    a.setAttribute('style', 'display:none');    
    a.setAttribute('target', '_blank');    
    a.setAttribute('download', name); //注意,一定要加这个  
    document.body.appendChild(a);  
    a.click();  
    a.parentNode.removeChild(a);    
}  
原文地址:https://www.cnblogs.com/miharu/p/7682358.html