Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách lấy URL hiện tại với JavaScript

Để lấy URL hiện tại, dùng thuộc tính window.location.href.

Ví dụ

<!DOCTYPE html>
<html>
  <body>
    <h3>Get current URL</h3>
    <p id="test"></p>
    <script>
      document.getElementById("test").innerHTML = "URL of the page: " + window.location.href;
    </script>
  </body>
</html>

Các property hữu ích của window.location:

  • href – URL đầy đủ
  • protocol – giao thức (http:, https:)
  • host – host:port
  • hostname – tên miền
  • port – cổng
  • pathname – đường dẫn
  • search – query string (?...)
  • hash – fragment (#...)
  • origin – protocol + host