What is the use of window.location
- First we can use it for getting the value of current web page address or URL
- Second For redirecting the current page to new page.
Some Types Of Window location
There are 5 basic types o window.location. All 5 types will do different work.
Window Location Href ( window.location.href )
The window.location.href gives us the current web page address or URL and it can redirect the current page also.
Get The Current Page URL
var OP = window.location.href;
if your current page url is – https://something.com/test
then the window.location.href will set “https://something.com/test” the value of variable OP
Redirect The Current Page
For redirecting the current page URL we will manually set the value of window.location.href.
window.location.href = 'https://google.com';
Window Location Hostname ( window.location.hostname )
window.location.hostname gives us the name of domain of current page or Hostname.
Hostname means where the files are hosted.
if you open a URL ex- google.com/login then the hostname for this page is google.com
var op = window.location.hostname;
If this code is written in this page – www.anything.com/blog/test.html
then script will set www.anything.com as the value of variable op
Window Location Pathname (window.location.pathname)
window.location.pathname gives us the path address of the current page.
If You are in this page ex – www.itscybertech.com/p/about.html
then the path name for the above url is /p/about.html
var op = window.location.pathname;
Window Location Protocol (window.location.protocol)
The window.location.protocol gives us the web protocol of the current URL
if you are visiting a site ex- https://facebook.com
then the webprotocol for the above URL is https:
var op = window.location.protocol;
Window Location Assign (window.location.assign)
The window.location.assign() simply load a new document or new URL.