我知道 Safari 会在 ajax 调用期间尝试通过 window.open() 阻止打开新选项卡。 我们需要在ajax调用之前调用window.open()来打开一个新选项卡,这样程序就可以防止Safari的阻塞。 参考上面,window.open(url, '_blank');无法在 iMac/Safari 上工作。
但是,如果我想使用 ajax 调用中的信息来验证是否需要打开新选项卡,即有条件地打开新选项卡取决于 ajax 调用的验证,该怎么办?
然后我无法在ajax调用之前打开新选项卡。这是因为如果验证没有通过,那么我需要关闭在ajax调用之前打开的选项卡...,这不是我想要的程序行为。
如果信息是通过 ajax 调用验证的,我怎样才能打开一个新选项卡?谢谢大家的回答!
let newTab = window.open();
someAjaxChecking(...).then((isValid)=>{
// isValid is a return boolean from the ajax calling someAjaxChecking() to
// determine whether redirect the new tab or close it
if(isValid){
newTab.location = url;
}else{
newTab.close(); // ***it is not desire to open and close the new tab...
}
})
真实案例:
如果我从用户角度理解您网站上发生的情况是这样的:
现在,你无法实现第三步,因为浏览器不允许你这样做。
但是,您可以通过用户操作(例如单击按钮或其他元素)触发的回调打开新窗口。
解决方案可能是:
另一个解决方案是:
如果您发出同步请求,它就会起作用。也许不是您理想的答案,但请查看以下片段:
<!DOCTYPE html>
<html>
<head>
<title>Parent Window</title>
</head>
<body>
<h1>Parent Window</h1>
<button onclick="openChildWindow()">Open Child Window</button>
<script>
let childWindow;
window.name = "parent";
async function openChildWindow() {
function fetchData(url) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, false); // Make the request synchronous
xhr.send();
if (xhr.status === 200) {
return JSON.parse(xhr.responseText);
} else {
throw new Error('Request failed with status:', xhr.status);
}
}
try {
const data = fetchData('https://jsonplaceholder.typicode.com/todos/1');
console.log('Data:', data);
} catch (error) {
console.error('Error:', error);
}
childWindow = window.open('https://www.google.com', 'ChildWindowTab');
}
</script>
</body>
</html>