Explain Codes LogoExplain Codes Logo

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

javascript
event-driven-programming
popup-blockers
ajax-calls
Anton ShumikhinbyAnton Shumikhin·Aug 28, 2024
TLDR

To open a URL in a new tab using JavaScript, the window.open() function combined with the '_blank' target does the trick:

window.open('https://www.example.com', '_blank').focus();

It feels like a magic spell, right? And as any good wizard, you need to know your magic comes in parts:

  1. window.open(): Your magic wand in the realm of browsers.
  2. '_blank': Here you're instructing your magic spell to open a URL in a new tab.

But we live in a "muggle" world, where pop-up blockers roam free. Let's learn some defense against pop-up blockers:

function openInNewTab(url) { const newWindow = window.open(url, '_blank'); if (newWindow) newWindow.opener = null; }

Wrap the code above in a function to reuse it, or to attach it to onclick events for bypassing those tricky pop-up blockers.

Event handling and popup blockers

Get interactive with your user-triggered events, such as onclick. Event-driven navigation is the most popular sport in Browserland:

document.getElementById('yourElementId').addEventListener('click', function() { openInNewTab('https://www.example.com'); });

That simple line of code is like sending an invitation to all the DOM elements of the party and ensuring none of them will be blocked by any bouncer (a.k.a. pop-up blockers).

But wait, there's more!

All browsers are not created equal. Chrome, for instance, might play hide and seek with you, opening a new window instead of a tab. So, stay frosty and test across different browsers (even that old school Internet Explorer) to ensure a consistent user experience.

Securing your new tabs

When creating tabs dynamically, it's vital to secure your URLs, especially if they are from user inputs. Use rel='noopener noreferrer' to prevent any potential phishing attacks:

let link = document.createElement('a'); link.target = '_blank'; link.rel = 'noopener noreferrer'; link.href = 'https://www.example.com'; document.body.appendChild(link); link.click(); document.body.removeChild(link);

That's your shield against the dark arts in the war of browsers!

AJAX and new tab navigation

In the realm of AJAX calls, you need to open a new window, even if the data isn't ready yet. To ensure Browserland doesn't explode, open the window directly within the click event's scope, and fill it in when the AJAX call finishes:

document.getElementById('fetcher').addEventListener('click', function() { let newWindow = window.open('about:blank', '_blank'); fetch('https://api.example.com/data') .then(response => response.text()) .then(text => { newWindow.document.body.textContent = text; }); });

It's a pro tip - opening windows early and filling them in late keeps browsers happy and wards off potential popup blockers.