最近公司开发的一个项目,平凡用到下载各类类型的文件,可是例如.txt,.jpg,.pdf格式的文件呢浏览器会在当前窗口直接打开,影响用户体验,尝试各类方案和百度总结一下几点;javascript
<a href="https://www.baidu.com" title="">Welcome</a>
等效于js代码java
window.location.href="https://www.baidu.com"; //在同当前窗口中打开窗口ajax
<a href="https://www.baidu.com/" title=""target="_blank">Welcome</a>
等效于js代码json
window.open("https://www.baidu.com/"); //在另外新建窗口中打开窗口浏览器
给出以下函数,将此函数绑定到click的事件回调中,就能够避免大部分浏览器对窗口弹出 的拦截:app
function newWin(url, id) { var a = document.createElement(‘a‘); a.setAttribute(‘href‘, url); a.setAttribute(‘target‘, ‘_blank‘); a.setAttribute(‘id‘, id); // 防止反复添加 if(!document.getElementById(id)) { document.body.appendChild(a); } a.click(); } function openUrl(url) { var a = $('<a href="'+url+'" target="_blank"></a>')[0]; var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true); a.dispatchEvent(e); } //调用方法newWin(url,'bbb') / openUrl(url) //原理都是经过建立一个a标签对象,经过里面自带的target执行跳转
//这样用户点击这个超连接,浏览器会认为它是打开一个新的连接,因此就不会拦 截。异步
<a href="javascript:void(0)" onclick="window.open()"></a>
//注意这里的超时时间不能过短,不然也会被拦截。async
setTimeout('window.open(url);', 500);
//先用window.open打开一个窗口,而后修改地址。如:函数
var tempwindow=window.open('_blank');
解决1:post
click: () => { var tempwindow=window.open();//先打开临时窗体,因为是点击事件内触发,不会被拦截 this.$http.get(url+id, {emulateJSON: true} ).then(response => { let resd = response.data; if(resd.code==0){ tempwindow.location.href = resd.result//当回调的时候更改临时窗体的路径 } else{ tempwindow.close()//回调发现无需打开窗体时能够关闭以前的临时窗体 this.$Message.error(resd.message) } }, response => { tempwindow.close()//回调发现无需打开窗体时能够关闭以前的临时窗体 console.log('error:', response) //for debug }); }
解决2:
click: () => { var flag = false; $.ajax({ 'url': url+id, 'type': 'post', 'dataType': 'json', 'data': data, 'async':false,//同步请求 success: function (data) { $("#a").attr("href","www.baidu.com");//当回调的时候更改页面上或建立的某个a标签的href flag = true;//更改标志 }, error:function(){ } }); if(flag){ $("#a")[0].click();//href属性更改后模拟点击 } }