38

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 :)

3

8 Answers 8

119

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"
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

2 Comments

Can you provide some details in your answer?
Hey Prikryl I have edited my answer .Did you get it now?
1

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

Comments

0

Try this

document.location.host

Comments

0

Use alert(window.location.origin) for getting the url.

Comments

0

Try

document.location.origin

That will give you the protocol and host.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.