window.open fails to open new page in ios safari

Last week, I wrote a small demand on the mobile terminal and encountered a problem: window.open failed to open a new page in ios safari. Record it again (the solution is at the end of the article).
The requirement at the time was: click the button on page A, send a request, and the request returns a url (this url is a third-party website address), and then the front end uses this url to jump to the third-party page.
It was originally a very simple requirement, but after the deployment, it was found that everything was normal on Android, but there was a problem on the ios phone: after clicking the button, the entire page did not respond. (In fact, if you add the loading effect, you can see the process of liaading, and you can also capture the request with the packet capture tool, but there is no next step after the request is successful.) The initial code is
:
insert image description here

const params = { ... // 请求参数, 这里略过 };
try {
      data.isLoading = true;
      const res: any = await authorizeGetNewUrl(params);
      window.open(res.data);
    } catch {
      data.isLoading = false;
    } finally {
      data.isLoading = false;
    }

It is the jump written in then, but an online search found that: because the safari browser has some security policies, it is forbidden to execute the window.open method in the callback function to prevent the page from popping up continuously.
For example:
Effective opening: If you obtain the file address in advance, then click to trigger the download to take effect:
window.open(url)
Invalid opening: If you first send a request to obtain the address, and then trigger the download in the successful callback of the request It will not take effect:
axios.get('xxx').then((url) => { window.open(url, '_blank'); }); Later, I tried to use the a label to jump, but it also failed:


const params = { ... // 请求参数, 这里略过 };
 try {
      data.isLoading = true;
      const res: any = await authorizeGetNewUrl(params);
      const a = document.createElement("a");
      a.target = "_blank";
      a.href = res.data;
      a.click();
    } catch {
      data.isLoading = false;
    } finally {
      data.isLoading = false;
    }

Final solution: window.location.href

const params = { ... // 请求参数, 这里略过 };
try {
      data.isLoading = true;
      const res: any = await authorizeGetNewUrl(params);
      window.location.href = res.data;
    } catch {
      data.isLoading = false;
    } finally {
      data.isLoading = false;
    }

insert image description here
Hope this article helps you!

Guess you like

Origin blog.csdn.net/JaneLittle/article/details/127112241