Safari 上与 window.open() 相关的问题

问题描述 投票:0回答:2

我知道 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...
   }

})

真实案例:

  • 我需要向我的后弯发送一个表单(数据集)来验证表单(AJAX 调用);
  • 然后会返回一个boolean(isValid)来判断表单是否有效;
  • 如果 boolean(isValid) 为 true,它将打开一个新选项卡
javascript html ajax safari window.open
2个回答
2
投票

如果我从用户角度理解您网站上发生的情况是这样的:

  • 用户采取行动(例如单击按钮)
  • 您执行异步 AJAX 调用
  • 成功(回调)后,将打开一个新窗口

现在,你无法实现第三步,因为浏览器不允许你这样做。

但是,您可以通过用户操作(例如单击按钮或其他元素)触发的回调打开新窗口。


解决方案可能是:

  • 获得要验证的数据后立即执行 AJAX 调用
  • AJAX回调存储结果(成功或不成功)。如果成功启用/显示按钮以打开新窗口
  • 单击(启用)按钮会触发打开新窗口的功能

另一个解决方案是:

  • 用户输入数据
  • 用户单击按钮
  • 执行 AJAX 调用 同步
  • 如果验证成功则打开新窗口

0
投票

如果您发出同步请求,它就会起作用。也许不是您理想的答案,但请查看以下片段:

<!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>

© www.soinside.com 2019 - 2024. All rights reserved.