Home >Web Front-end >JS Tutorial >What's the Difference Between `window.location.href` and `window.open()` in JavaScript?
The Subtle Distinction: window.location.href vs. window.open() in JavaScript
When it comes to navigating browsers and opening new windows, JavaScript offers two essential tools: window.location.href and window.open(). While these methods serve similar purposes, they differ in their functionality.
window.location.href
window.location.href is not actually a method, but rather a property that stores the current URL of the browser. It's primarily used to retrieve the URL of the current page. However, you can also set the value of window.location.href to change the browser's location, effectively redirecting the page to a new URL.
window.open()
In contrast, window.open() is a method that enables you to open a new window or tab and load a specified URL into it. This method takes a single parameter, which is the URL you want to open. By passing different URLs, you can populate the new window or tab with distinct content.
Usage Examples
To illustrate their usage:
For window.location.href:
<code class="javascript">window.location.href = 'http://www.example.com'; // Redirects to www.example.com</code>
For window.open():
<code class="javascript">window.open('http://www.example.com'); // Opens www.example.com in a new window</code>
Additional Points
The above is the detailed content of What's the Difference Between `window.location.href` and `window.open()` in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!