I’m working on a feature where I send a request to a server and receive a response. The response may or may not include a URL. If a URL is present in the response:
- I need to open that URL in a new browser tab.
- Simultaneously, I want to redirect the current tab to another page.
However, I’m facing issues with mobile browsers blocking the new tab because the window.open action doesn’t occur as a direct result of the user’s interaction (e.g., a click).
Additionally, opening a tab ahead of time (before the response is received) isn’t an option. The request is triggered by a form button, which also switches steps in the form. Since the response may not always contain a URL, I can’t open a new tab in advance for every button click.
- Here’s what I’ve tried so far:
fetch('/api/some-endpoint')
.then(response => response.json())
.then(data => {
if (data.url) {
window.open(data.url, '_blank');
}
window.location.href = '/another-page';
});
- Expectation: Open the URL in a new tab and redirect the current tab.
- Result: Works on desktop, but mobile browsers block the new tab.
- Creating a link dynamically and emulating a click:
const link = document.createElement('a');
link.href = data.url;
link.target = '_blank';
link.click();
- Expectation: Avoid triggering popup blockers.
- Result: Did not work; the new tab is still blocked.
Is there a reliable way to achieve this functionality, especially on mobile browsers? Or any alternative approaches to handle this scenario?