小能豆

Open a URL in a new tab (and not a new window)

javascript

I’m trying to open a URL in a new tab, as opposed to a popup window.

I’ve seen related questions where the responses would look something like:

window.open(url,'_blank');
window.open(url);

But none of them worked for me, the browser still tried to open a popup window.


阅读 204

收藏
2023-12-27

共1个答案

小能豆

In modern web browsers, opening a URL in a new tab or new window is ultimately controlled by the browser’s settings and user preferences. However, you can use the following approach to attempt to open a URL in a new tab:

var win = window.open(url, '_blank');
if (win) {
    // Browser has allowed the new tab/window to be opened
    win.focus();
} else {
    // Browser has blocked the new tab/window, provide a fallback or inform the user
    alert('Please allow pop-ups for this site to open in a new tab.');
}

This code tries to open the URL in a new tab with window.open(url, '_blank'). If the browser allows it, the win variable will reference the new window/tab. However, if the browser’s pop-up blocker prevents it, win will be null. In such cases, you can provide a fallback or inform the user about enabling pop-ups for your site.

Keep in mind that browsers have become more restrictive with pop-ups for user experience and security reasons. Users can usually configure their browsers to allow or block pop-ups, and some browsers may still treat certain window.open requests as pop-ups rather than opening them in a new tab.

Additionally, this behavior might vary between different browsers and their versions. If you’re facing specific issues with a particular browser, you may want to check its documentation or community forums for any browser-specific considerations.

2023-12-27