Javascript Get Site URL

How do I get Javascript to tell me the website url.

For example, if I have a page www.example.com/page.html

I want Javascript to tell me that the URL is www.example.com , not www.example.com/page.html (which document.location reports)

Is there any way to do this? If so, how?

Thanks in advance for your help :)

+7
javascript
source share
8 answers

There are several ways to do this, but one way might be better for certain situations (for example, inside an iFrame).

Protocol + Domain + Page

 document.URL > "http://example.com/page1.html" document.location.href > "http://example.com/page1.html" 

Protocol + Domain

 document.location.origin > "http://example.com" 

Domain

 document.location.host > "example.com" 

Page

 document.location.pathname > "/page1.html" 
+42
source share

try it

 document.location.host 
0
source share

Use alert (window.location.origin) to get the url.

0
source share

Try

 document.location.origin 

This will give you the protocol and host.

0
source share

Using

 window.location.hostname 

You can test it by simply typing it into the chrome dev tool console

Link

MDN: https://developer.mozilla.org/en-US/docs/Web/API/Location

0
source share

There are many ways to get this.
Open the Chrome browser and press F12, you will get a console.

Enter the following commands for the same question. You will get an answer

 window.location.hostname // Output : stackoverflow.com window.location.origin // Output : http://stackoverflow.com document.location.host // Output : stackoverflow.com 
0
source share

using

 document.location.origin+document.location.pathname; 

where document.location.origin redirect you to "http://www" and document.location.pathname redirect you to "/ stackoverflow /" (the name of your project). That way you can provide a link to a page or post in the js file. Please, if I want a link to my home page, I would use

 var address=document.location.origin+document.location.pathname; window.location.replace(address+"/home"); 

Thus, using the example above, I can easily redirect to the home page

0
source share

It can help you.

Link: w3Resource

JavaScript version

 //Write a JavaScript program to get the website URL (loading page) alert(document.URL); 

ES6 Version

 //Write a JavaScript program to get the website URL (loading page) alert(document.URL); 
0
source share

All Articles