k300
k300

Reputation: 431

Javascript Get Website URL

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

Answers (8)

sandeepsinghnegi
sandeepsinghnegi

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

Naved Ali
Naved Ali

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

stewart715
stewart715

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

Nishu Tayal
Nishu Tayal

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

Shamps
Shamps

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

Jaime Torres
Jaime Torres

Reputation: 10515

Try

document.location.origin

That will give you the protocol and host.

Upvotes: 0

deepakborania
deepakborania

Reputation: 166

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

Upvotes: 0

Max
Max

Reputation: 156

Try this

document.location.host

Upvotes: 0

Related Questions