通过$nextTick执行window.open谈chrome的拦截机制及解决方案

今天在 $nextTick的回调中,用了window.open,发现不能打开新窗口了。搞了半天才发现是被chrome拦截了(怪我眼拙没看见…)。

后来搜了一下chrome的拦截机制,发现是因为chrome阻止了非用户触发的window.open。

先贴上代码:

<el-menu-item :index="item[1].src" :class="{openWindow: item[1].src === hasOpenWindow}" @click="open(item[1].src)" :data-open="item[1].openItem" >xxx</el-menu-item>
open (url) {
	// 在更新完DOM后再执行
	this.$nextTick(() => {
		let openWindow = document.querySelector('.openWindow');
		// 如果data-open属性是true则可以打开新页面,且不会刷新iframe或打开router-view
		if (openWindow.dataset.open) {	// 改为原生js获取自定义属性
			let width = 550;
			let height = 373;
			let top = (window.screen.availHeight - height) / 2;
			let left = (window.screen.availWidth - width) / 2;
			window.open(url, 'newwindow', 'height=' + height + ',width = ' + width + ',top = ' + top + ',left = ' + left + 'toolbar = no,menubar=no,scrollbars=no,location=no,status=no');
		}
		if (!openWindow.dataset.open) {	// open === false  再显示iframe
			this.changeView(false);		// 不显示router-view
			// 子组件向父组件传
			this.$emit('getIframeSrc', url);
		}
	});
}

可以看到,因为window.open被写在了$nextTick的回调里面,即使我们触发了open事件,此时是在回调的上下文中,并不在被点击的open事件里面了,也就不算是用户点击触发的了。自然chrome就给屏蔽掉了。

关于解决方案, 可以改用 setTimeout 或者可以看这个chrome拦截window.open弹窗问题的两种解决方式

参考:chrome拦截window.open弹窗问题的两种解决方式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值