Explain Codes LogoExplain Codes Logo

Make a link open a new window (not tab)

javascript
window-open
pop-up-blockers
browser-behaviors
Nikita BarsukovbyNikita Barsukov·Aug 5, 2024
TLDR

Ensuring a link opens in a new window rather than a tab involves implementing the <a> tag's target to _blank along with window specifications via the onclick event. Here's the JavaScript code:

<a href="javascript:void(0);" onclick="window.open('https://www.example.com', 'newWin', 'width=500, height=300');">Open New Window</a>

This syntax results in the URL https://www.example.com opening in a new window with dimensions 500x300px. Bear in mind that pop-up blockers or specific browser settings may alter this behavior.

Handling Pops-up Blockers

Modern browsers tend to come equipped with pop-up blockers that might prevent the window.open() method from working as expected. It's recommended to advise users that they might need to allow pop-ups for your website, or provide an alternative means of navigation.

Understanding Browser Behaviors

Browsers have the ultimate say on how target="_blank" is interpreted — the norm is opening a new tab rather than a new window. Both Chrome and Firefox prefer tabs over new windows, providing a more fluid user experience. Although you can't overrule the browser's default behavior with mere HTML, you can certainly suggest window sizes with JavaScript.

Cross-Browser Consistency

To ensure the window.open() method works seamlessly across browsers and platforms, it's necessary to consider certain aspects, such as how it performs on mobile devices where the support for new windows is limited or non-existent. Checking your implementation on different browsers and being aware of potential limitations aids in maintaining a consistent user experience.

Evaluating Security Concerns

window.open() seems like an easy solution, but it should be mentioned that it may be blocked by browsers considering its reputation of being utilized for spam and similar unwelcome behaviors. As a result, this function often requires user interaction, like a click, to prevent unwanted intrusions.

Proficient Use of JavaScript Frameworks

While you can indeed implement window.open() with frameworks like jQuery, the bare-bone method remains the same — acting as a syntactic sugar and not providing any additional control or abilities to bypass browser behaviors.

Historical Context and Modern Standards

Be mindful of HTML5 standards, while it used to be common to see target="new" to indicate a new window, these days it's best to utilize _blank for new browsing contexts, making it a safer, more current option.