当window.open为用户触发事件内部或者加载时,不会被拦截,一旦将弹出代码移动到一段异步代码内部,马上就出现被拦截的表现了。
当浏览器检测到非用户操作产生的新弹出窗口,则会对其进行阻止。因为浏览器认为这可能是一个广告,不是一个用户希望看到的页面。
解决方案一:
- 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();
- }
这种方案不适用与异步代码中。
解决方案二:
let newWindow = window.open("about:blank","_blank");
- $.ajax({
- type: "post",
- url: "/xxxx/xxxx",
- data: {"param": param},
- error: function (data) {
- showError(data);
- },
- success: function (data) {
- if (data.errorFlag == 0) {
- // 新加
- newTab.location.href = "www.baidu";
- } else {
- layer.alert(data.desc, {icon: 2, title: '提示信息'})
- }
- }
- });