Problem Description:

When the browser detects a new pop-up created by a non-user action, it blocks it. Because the browser thinks this is not a page the user wants to see. This behavior varies between browsers and versions.

Scene:

Before a file download operation or a new page is triggered after the user clicks, the interface needs to be called for judgment (such as permissions, task execution progress, etc.).

The solution

  1. Use synchronous Ajax requests for pre-open judgment

Advantages: Compatible with all browsers. Disadvantages: blocks code execution, and the browser is in suspended state during the request pending phase; The browser will report a warning;

  1. Using a transfer page, a new page is opened and redirected or closed after the request is returned

Advantages: Currently used more methods, all browsers apply. Disadvantages: You need to open a new page regardless of whether you pass the test. User perception and prompt are not friendly

Available for download only:

  1. Apply the simulation A TAB click with the magical H5 Download attribute

Advantages:… Disadvantages: There are compatibility issues with the Download attribute && Download does not support cross-domain resources v< Download >

  1. Instead of window.open, use window.location.href for download

Advantages: Applicable to all browsers Disadvantages: can not download PDF/PNG browser can be directly opened resources; Background download interface can not report errors, otherwise the original page will be replaced, the experience is not friendly

Code:

  1. Use synchronous Ajax requests for pre-open judgment
ajax('get', url, false).then(() = > {
    window.open('http://www.baidu.com')})function ajax(type, url, isAsyac) {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        // The third argument determines whether it is asynchronous, true asynchronous
        xhr.open(type, url, isAsyac);
        xhr.onreadystatechange = function () {
            if(xhr.readyState === 4) {
                resolve(xhr.response)
            }
        }
        xhr.send()
    })
}
Copy the code
  1. Using a transfer page, a new page is opened and redirected or closed after the request is returned
var newWin = window.open('loading page')
ajax().then(res= > {
	newWin.location.href = 'target url'
}).catch(() = > {
	newWin.close()
})
Copy the code
  1. A tag simulates clicking
ajax().then(res= > {
	asyncOpen(res.url)
})

function asyncOpen(url) {
    var a = document.createElement('a')
    a.setAttribute('href', url)
    a.setAttribute("target"."_blank");
    a.setAttribute("download".'name');
    document.body.appendChild(a);
    a.click();
    a.remove();
}
Copy the code