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:
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!