javascript 取得目前網頁網址 (location)

by Hsiangming Lo

當你需要利用網址來進行判斷時,可以使用 location 來取得當前網址的資訊。

<script>
  // https://www.example.com/event/page/?p=1&s=2#hash
  location.hash;
  >> "#hash"

  location.host;
  >> "www.example.com"

  location.hostname;
  >> "www.example.com"

  location.href;
  >> "https://www.example.com/?p=1&s=2#hash"

  location.origin;
  >> "https://www.example.com"

  location.pathname;
  >> "/event/page/"

  location.port;
  >> "" // 大多數瀏覽器不會顯示默認端口(http:80,https:443)

  location.protocol;
  >> "https:"

  location.search;
  >> "?p=1&s=2"
</script>