window.open 被浏览器拦截解决方案

在项目开发中, 须要在按钮点击后发出一个ajax请求并在请求完成后, 弹出一个新窗口页面. 天然想到用window.open实现, 但会被浏览器拦截javascript

分析

当浏览器检测到非用户操做产生的新弹出窗口,则会对其进行阻止。由于浏览器认为这多是一个广告,不是一个用户但愿看到的页面。html

window.open为用户触发事件内部或者加载时,不会被拦截,一旦将弹出代码移动到ajax或者一段异步代码内部,立刻就出现被拦截的现象。java

被拦截示例代码

例如, 下面这段代码就会被拦截:ajax

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <h3>{{msg}}</h3>
    <button ref='btn' type="button" @click="clickHandler">click</button>
  </div>
</template>
<script> export default { props: { msg: { required: true, type: String } }, data () { return { url: 'http://www.baidu.com/', } }, mounted () { setTimeout(() => { window.open(this.url, '_blank') }, 100) } } </script>
复制代码

解决方案

1. 打开新窗口的代码绑定到click的事件回调中,就能够避免大部分浏览器对窗口弹出的拦截:

以下示例代码:浏览器

button的click事件触发的回调函数clickHandler内打开一个新窗口不会被浏览器拦截.异步

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <h3>{{msg}}</h3>
    <button ref='btn' type="button" @click="clickHandler">click</button>
  </div>
</template>
<script> export default { props: { msg: { required: true, type: String } }, data () { return { url: 'http://www.baidu.com/', } }, mounted () { }, methods: { clickHandler () { window.open(this.url, '_blank') } } } </script>
复制代码

2. 经过form表单提交实现(亲测, 会被拦截)

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <h3>{{msg}}</h3>
    <form action="http://www.baidu.com" ref="form" method="get" target="_blank" style="display: none"></form>
  </div>
</template>
<script> export default { props: { msg: { required: true, type: String } }, data () { return { url: 'http://www.baidu.com/', } }, mounted () { setTimeout(() => { this.$refs.form.submit() }, 1000) }, methods: { } } </script>
复制代码

将上面的代码改造下, form提交的事件由button按钮的click事件触发的话, 就不会被浏览器拦截函数

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <h3>{{msg}}</h3>
    <form action="http://www.baidu.com" ref="form" method="get" target="_blank" style="display: none"></form>
    <button type="button" @click='clickHandler'>button</button>
  </div>
</template>
<script> export default { props: { msg: { required: true, type: String } }, data () { return { url: 'http://www.baidu.com/', } }, mounted () {}, methods: { clickHandler () { this.$refs.form.submit() } } } </script>
复制代码

3. 先弹出窗口,而后重定向(最优方案)

先经过用户点击打开页面(必须是用户点击而触发的行为),而后再对页面进行重定向ui

<template>
  <div class="about">
    <h1>This is an about page</h1>
    <h3>{{msg}}</h3>
    <button ref="btn" @click="clickHandler">button</button>
  </div>
</template>
<script> export default { props: { msg: { required: true, type: String } }, data () { return { url: 'http://www.baidu.com/', newTab: null } }, mounted () {}, methods: { clickHandler () { this.newTab = window.open('about:blank') let $ajax = new Promise((resolve, reject) => { setTimeout(() => { resolve() }, 1000) }) $ajax.then(() => { this.newTab.location.href = this.url setTimeout(() => { this.newTab = null }, 1) }) } } } </script>

复制代码
相关文章
相关标签/搜索