window.open()仅在IOS中的异步函数中不工作

llycmphe  于 2023-05-19  发布在  iOS
关注(0)|答案(1)|浏览(244)

我开发了一个ReactJS应用程序,它嵌入了安卓和ios的webview中。
我有一个重定向到新网站的按钮。如果第一次点击该按钮,会触发API调用,然后使用window.open进行重定向,如果第二次点击,则不会触发api调用,直接应用重定向。
下面是代码

let windowReference = window.open("", "_blank");
  //first time
  if (reward == null) {
       let resp = await activate();
       if (resp.ok) {
            if (windowReference == null || windowReference.closed) {
                window.open(myUrl, "_blank");
            } else {
                windowReference.location = myUrl; 
            }
       }
  } else {
       //second time
      if (windowReference == null || windowReference.closed) {
                window.open(myUrl, "_blank");
            } else {
                windowReference.location = myUrl; 
            }
  }

这段代码在android webviewbrowser上工作正常,但在ios webview中,第一次它什么也不做,只是第二次单击导航到myUrl。
我试过的东西
1.将异步响应中的逻辑放在setTimeout
1.将_blank更改为_self
还是什么都没变
我是不是漏掉了什么。
请如果你能帮助让我知道。

lndjwyie

lndjwyie1#

我认为问题是默认情况下IOS Safari有一个严格的弹出窗口拦截器相比,其他浏览器,这可能会阻止它打开新窗口。
要解决此问题,您可以打开窗口以响应用户的手势。您也可以尝试在异步调用的单独函数中打开新窗口,但不要在异步函数中打开。
示例:

function handleOpenNewWindow() {
let windowReference = window.open("", "_blank");
if (windowReference == null || windowReference.closed) {
  window.open(myUrl, "_blank");
} else {
windowReference.location = myUrl;
 }
}
 //---  call handleOpenNewWindow() asynchronously here ---
 let resp = await activate();
 if (resp.ok) {
 setTimeout(handleOpenNewWindow, 0);
 }

相关问题