有時候在開發業務時,因爲產品體驗,要求自動打開新窗口,而不但願用戶手動點擊。
直接在代碼中執行:javascript
window.open('http://www.baidu.com')
html
是會被瀏覽器攔截的,瀏覽器是默認屏蔽彈出窗口,可是是用戶手動觸發,就不會攔截,若是是程序自動執行,則會攔截。java
那麼根據上述規則,那就在用戶有點擊動做時打開這個窗口,僞代碼以下:ajax
<a href="javascript:;" id="blank">test</a> document.getElementById('blank').onclick=function(){ window.open(...) }
示例在此編程
不過,這方式在異步編程中仍是會被攔截,因此在用戶點擊發送請求的同時打開一個新窗口,而後在回調函數中修改新窗口的地址,僞代碼以下:瀏覽器
<a href="javascript:;" id="blank">test</a> document.getElementById('blank').onclick=function(){ const newwin = window.open('about:blank'); $.ajax({ type: 'post', url: 'xxxx', data: {...}, }).then((data)=>{ ... newwin.location.href = data.href; // 調用location })