异步ajax无法使用js触发用户操作

289 阅读1分钟

某些版本的 chrome 和 firfox 浏览器不支持在异步ajax 回调中触发类似window.open() , element.click() 等响应的操作。 fetch方法也是一样的

const xhr = new XMLHttprequest();
xhr.onreadystatechange = function() {
	if(xhr.readyState === 4 && xhr.status === 200) {
    	//下面操作无效
        window.open(someUrl);
        element.click();
    }
}
xhr.open(...);
xhr.send();

解决方案: 使用同步ajax请求 DD

        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, false); // 第三个参数设置为false,意为同步请求
        xhr.send();
        if (xhr.status === 200) {
            const res = JSON.parse(xhr.response);
            if (res.status === 0) {
            	// 可以生效
                window.open(someUrl);
        		element.click();
            } else {
                
            }
        }