Reputation: 431
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 :)
Upvotes: 38
Views: 84666
Reputation: 292
you can also use location.href
= '/'
+ 'path_name/sub_path_name'
'/'
= takes you to the home page then
'path_name/sub_path_name'
= to pass the new path to the domain page
Upvotes: 0
Reputation: 637
use
document.location.origin+document.location.pathname;
where document.location.origin
will redirect you to "http://www"
and document.location.pathname
will redirect you to "/stackoverflow/"(Name of your project).
In this way you can give reference to page or post you want in your js file.Suppose if i want reference to my home page i would have use
var address=document.location.origin+document.location.pathname;
window.location.replace(address+"/home");
So using above example i can easily redirect to my homepage
Upvotes: 2
Reputation: 5647
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"
Upvotes: 118
Reputation: 20810
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
Upvotes: 3
Reputation: 508
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
Upvotes: 1
Reputation: 10515
Try
document.location.origin
That will give you the protocol and host.
Upvotes: 0