37

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

k300
  • 425
  • 1
  • 6
  • 10
  • [`Location` objects](https://developer.mozilla.org/en-US/docs/Web/API/Location) have various properties that represent each segment. – Jonathan Lonowski Oct 23 '13 at 19:01
  • possible duplicate of [Get current URL with JavaScript?](http://stackoverflow.com/questions/1034621/get-current-url-with-javascript) – isherwood Oct 23 '13 at 19:02
  • possible duplicate of [Get host name in JavaScript](http://stackoverflow.com/questions/1368264/get-host-name-in-javascript) – T.Todua Mar 19 '15 at 09:56

8 Answers8

114

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"
stewart715
  • 5,557
  • 11
  • 47
  • 80
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
Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101
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

Shamps
  • 488
  • 3
  • 11
1

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

Naved Ali
  • 616
  • 1
  • 14
  • 31
0

Try this

document.location.host
Bucket
  • 7,415
  • 9
  • 35
  • 45
Max
  • 156
  • 5
0

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

deepakborania
  • 166
  • 2
  • 8
0

Try

document.location.origin

That will give you the protocol and host.

Jaime Torres
  • 10,365
  • 1
  • 48
  • 56
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

sandeepnegi
  • 123
  • 13