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
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
There are many ways to get this.
Open Chrome browser and press F12, you'll get console.
Type following commands there for the same question URL. You will get your answer
window.location.hostname // Output : stackoverflow.com
window.location.origin // Output : http://stackoverflow.com
document.location.host // Output : stackoverflow.com
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"
Try this
document.location.host
Try
document.location.origin
That will give you the protocol and host.
Use alert(window.location.origin) for getting the url.