之前有個需求是輸入一些配置,然后點擊預覽,通過接口保存配置並返回預覽頁面鏈接,在新頁面中打開鏈接。后來測試一直說沒有新頁面打開,我一看,原來是被瀏覽器攔截了。
原因如下:
瀏覽器只有在認為click和submit在打開新窗口時(如果是_self則不會有此限制),這些操作是由用戶主動觸發時才是安全可以被執行,而ajax回調函數中去執行click和submit被瀏覽器認為不是由用戶主動觸發的,因此不能被安全執行,所以被攔截。
解決方法:
新打開一個標簽頁,在請求響應后,改變新標簽頁的href。
let newWindow = window.open() this.$http.post(/, query).then(function(response) { if (response.body.success == true) { newWindow.location.href = this.$api.config.screenUrl + this.id } }
在查詢解決方法的過程中,我還嘗試了新建一個a標簽的方式,但是依舊會被攔截。原因應該如上。把創建a標簽的辦法放上來,可以參考一下。
function newWin(url, id) { var a = document.createElement('a') a.setAttribute('href', url) a.setAttribute('target', '_blank') a.setAttribute('id', id) a.style.visibility = 'hidden' // 防止反復添加 if(!document.getElementById(id)) { document.body.appendChild(a) } a.click(); }