在項目開發中, 須要在按鈕點擊後發出一個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>
複製代碼
以下示例代碼:瀏覽器
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>
複製代碼
<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>
複製代碼
先經過用戶點擊打開頁面(必須是用戶點擊而觸發的行爲),而後再對頁面進行重定向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>
複製代碼