Home  >  Article  >  Web Front-end  >  How to Open URLs in New Windows/Tabs with JavaScript?

How to Open URLs in New Windows/Tabs with JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-21 21:23:30717browse

How to Open URLs in New Windows/Tabs with JavaScript?

Opening URLs in New Windows/Tabs Using JavaScript

In JavaScript, the location.href property allows you to change the URL of the current page. However, when used directly, it replaces the current page with the target URL. To open the target URL in a new window or tab, you need to utilize the window.open() method.

Example

Consider the following JavaScript code fragment:

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

To open the target URL in a new tab, modify the code as follows:

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

In this modified code, we invoke the window.open() method with two parameters:

  • The first parameter ('https://support.wwf.org.uk/earth_hour/index.php?type=individual') specifies the URL to be opened.
  • The second parameter ('_blank') indicates that the URL should be opened in a new window tab.

Note: The '_blank' target value can also be used to open the URL in a new window. However, different browsers may have different behaviors when using '_blank' for window-based targets. Therefore, it's generally recommended to use '_blank' for tab-based targets and a specific window name for window-based targets.

The above is the detailed content of How to Open URLs in New Windows/Tabs 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