Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-21 21:23:30
Original
717 people have browsed it

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";
}
Copy after login

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.
  );
}
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!