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 the site url is www.example.com
and not www.example.com/page.html
(which document.location tells me)
Is there a way to do this? If so, how?
Thanks in advance for your help :)
Full current URL refers to the document path (external address).
There are several ways you can do this, but one way might be best for certain situations (e.g. within 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"
Use
window.location.hostname
You can test it by just typing it in the chrome dev tools console
Reference
MDN: https://developer.mozilla.org/en-US/docs/Web/API/Location
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With