Javascript Get Website URL

后端 未结 7 1976
别那么骄傲
别那么骄傲 2020-12-29 05: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

相关标签:
7条回答
  • 2020-12-29 06:14

    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

    0 讨论(0)
  • 2020-12-29 06:17

    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
    
    0 讨论(0)
  • 2020-12-29 06:19

    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"
    
    0 讨论(0)
  • 2020-12-29 06:21

    Try this

    document.location.host
    
    0 讨论(0)
  • 2020-12-29 06:28

    Try

    document.location.origin
    

    That will give you the protocol and host.

    0 讨论(0)
  • 2020-12-29 06:30

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

    0 讨论(0)
提交回复
热议问题