Home  >  Article  >  Web Front-end  >  How to Open URLs in a New Browser Tab with JavaScript?

How to Open URLs in a New Browser Tab with JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-21 21:20:03606browse

How to Open URLs in a New Browser Tab with JavaScript?

Opening URLs in New Browser Tabs with JavaScript's 'location.href': A Comprehensive Solution

While JavaScript's 'location.href' property allows developers to change the current page's location, it has limitations when users seek to open a new tab. To address this, an alternative approach is required to navigate the desired URL in a separate browser tab.

The solution involves leveraging JavaScript's 'window.open()' function. This powerful method accepts two parameters:

  1. 'targetURL': The URL that should be opened in the new tab.
  2. 'windowFeatures': A string indicating how the new window should be opened. For a new tab, specify '_blank'.

By replacing the original code:

if (command == 'lightbox') {
 location.href="https://support.wwf.org.uk/earth_hour/index.php?type=individual";
}

with the following improved version, you can successfully open the target URL in a new browser tab:

if (command == 'lightbox') {
 window.open(
  'https://support.wwf.org.uk/earth_hour/index.php?type=individual',
  '_blank'
 );
}

This enhanced code snippet will create a new browser tab and flawlessly load the intended webpage without overwriting the current tab's content.

The above is the detailed content of How to Open URLs in a New Browser Tab with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn