location.host vs location.hostname and cross-browser compatibility?

后端 未结 6 1435
情话喂你
情话喂你 2020-11-29 14:59

Which one of these is the most effective vs checking if the user agent is accessing via the correct domain.

We would like to show a small js based \'top bar\' style

相关标签:
6条回答
  • 2020-11-29 15:14

    host just includes the port number if there is one specified. If there is no port number specifically in the URL, then it returns the same as hostname. You pick whether you care to match the port number or not. See https://developer.mozilla.org/en/window.location for more info.

    I would assume you want hostname to just get the site name.

    0 讨论(0)
  • 2020-11-29 15:17

    Just to add a note that Google Chrome browser has origin attribute for the location. which gives you the entire domain from protocol to the port number as shown in the below screenshot.

    0 讨论(0)
  • 2020-11-29 15:18

    As a little memo: the interactive link anatomy

    --

    In short (assuming a location of http://example.org:8888/foo/bar#bang):

    • hostname gives you example.org
    • host gives you example.org:8888
    0 讨论(0)
  • 2020-11-29 15:24

    Your primary question has been answered above. I just wanted to point out that the regex you're using has a bug. It will also succeed on foo-domain.com which is not a subdomain of domain.com

    What you really want is this:

    /(^|\.)domain\.com$/
    
    0 讨论(0)
  • 2020-11-29 15:31

    MDN: https://developer.mozilla.org/en/DOM/window.location

    It seems that you will get the same result for both, but hostname contains clear host name without brackets or port number.

    0 讨论(0)
  • 2020-11-29 15:35

    If you are insisting to use the window.location.origin You can put this in top of your code before reading the origin

    if (!window.location.origin) {
      window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
    }
    

    Solution

    PS: For the record, it was actually the original question. It was already edited :)

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