I'm trying to open a new tab with a given URL programmatically in React.
const navigate = (href) => {
try {
$(`<a href="${href}" target="_blank"></a>`)[0].click();
} catch (ex) {
console.log(ex);
window.open(href, `_newtab${Math.floor(Math.random() * 999999)}`) ||
window.location.replace(href);
}
};
The jQuery solution works best, however it doesn't always work - for example in Safari on iPhones, this does nothing.
The
window.open(href, `_newtab${Math.floor(Math.random() * 999999)}`) ||
window.location.replace(href);
is less effective as sometimes it opens a popup, and sometimes it opens the new link in the same tab as my application. However, it works on all devices.
What I would like to do is try the jQuery solution first, and if this doesn't do anything, trigger the second option as backup.
However, I noticed that when
$(`<a href="${href}" target="_blank"></a>`)[0].click();
fails on iPhone, it doesn't actually trigger an exception, so the catch block never executes.
Is there another way I can approach this?
I looked at this question to create the above function: javascript window.location in new tab