window.open打开网址被拦截

window.open打开网址被拦截

标签: js


坑位

通过window.open打开一个网址,在火狐和IE系列浏览器下会拦截掉,除非用户主动点击允许才会成功,这样用户体验基本是恶心到产品的,而产品又不希望通过location.href来解决。

Why

应该是浏览器的安全案例策略有关,当浏览器检测到非用户操作产生的新弹出窗口,则会对其进行阻止。因为浏览器认为这可能是一个广告,不是一个用户希望看到的页面

解决方案

1 使用a标签替代,动态生成一个a标签,再把要跳转的地址赋与href,再主动触发它的click事件,或者在页面底部写一个样式为display:none的a标签,再手动触发点击事件。测试地址

/**
 * 
 * @param {string} url 要跳转的url
 */
function newWin(url) {  
  var aElement = document.createElement("a");  
  aElement.setAttribute("href", url);  
  aElement.setAttribute("target", "_blank");  
  aElement.click();  
}

2 通过表单提交来跳转,通过设置表单action为跳转地址,新窗口提交target="_blank"来实现。测试地址

<form id="testform" target="_blank" action="https://www.baidu.com" method="get"></form>
  <button id="testbtn">点击跳转</button>
  <script type="test/css">
    document.querySelector("#testbtn").onclick = function() {
      document.querySelector("#testform").submit()
    }
  </script>
posted @ 2020-06-18 23:07  !win !  阅读(591)  评论(0编辑  收藏  举报