up
down
Close
架站盒子
Web Development Box
 

JavaScript抓當前網頁的網址或參數

│ 3826 Views │ JavaScript

取得完整網址

<script>
console.log('location.href: '+location.href); // http://kumo.tw:80/test.php?post=123#456
</script>

取得網址部分參數

假設網址為:https://kumo.tw:80/test.php?post=123#456 <script>
console.log('location.protocol: '+location.protocol); // https:
console.log('location.hostname: '+location.hostname); // kumo.tw
console.log('location.host: '+location.host); // kumo.tw
console.log('location.port: '+location.port); // 80
console.log('location.pathname: '+location.pathname); // /test.php
console.log('location.search: '+location.search); // ?post=123
console.log('location.hash: '+location.hash); // #456
</script>

說明

要取得當前網頁的網址只需要用 location.href,如果要取得其中的參數則如上述各項語法,請針對需求使用即可。

範例

本頁已設置語法,請按 F12 > console(主控台) 檢查結果,空白部分代表本頁網址沒有該資料。

延伸閱讀

    暫無相關文章…
    本文是否對您有幫助?