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>

複製代碼
相關文章
相關標籤/搜索