Many times you want to load a web page from your application. You can create a hyper link but you might want to change the page on click of a button or some other event.
In such cases, javascript’s page redirection can be used. There are following three ways in which you can load a new URL or redirect to another page using javascript.
Method 1: Using window.location.href property
Javascript’s window.location
object has an href
property which represents the URL of current page. Assign this property to the desired URL and it will load the supplied URL in the current page. Example,
window.location.href = ‘https://google.com’;
Remember that http:// or https:// before the URL is necessary else it will not load the new URL but only reload the current URL.
Method 2: Using window.location.replace method
Javascript’s window.location
property has a replace
method which takes a URL as argument in string format and changes the current URL to that supplied.
To know the URL of current page in javascript, refer this post.
Again the URL should be preceded with http:// or https:// else only the current URL will reloaded.
window.location.replace(‘http://google.com’);
Method 3: Using window.open method
open
method of window object takes a URL in the form of a string as argument and loads the supplied URL in a new browser window. Example,
window.open(‘http://google.com’);
If the URL is not preceded with http:// or or https://, then it will load the same URL that is open in the current window in the new window too.
Also remember that this method will load the new page in a new browser window.
If you found this post helpful, then press the clap button below.