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

Cách lấy giao thức (protocol) và đường dẫn trang (page path) của trang web hiện tại trong JavaScript


JavaScript cung cấp location object để lấy chi tiết trang web hiện tại. Đối tượng này có window.location.protocol và window.location.pathname để lấy giao thức và đường dẫn tương ứng. Thảo luận chi tiết.

Đường dẫn (Pathname)

Mọi website đều có pathname. location object cung cấp window.location.pathname để lấy nó.

Ví dụ

<html> <body> <p id="pathname"></p> <script> document.getElementById("pathname").innerHTML = "Page path is: " + window.location.pathname; </script> </body> </html>

Kết quả

Page path is: /cg/assets/jgCOmn.php

Giao thức (Protocol)

Thường site bắt đầu bằng https://. Đó là giao thức của site. Giao thức định dạng cách tin nhắn được truyền, hành động server/trình duyệt nên thực hiện.

Ví dụ

<html> <body> <p id="protoname"></p> <script> document.getElementById("protoname").innerHTML = "Protocol name is: " + window.location.protocol; </script> </body> </html>

Kết quả

The page protocol is: https: