在客戶端腳本中,經常需要獲取用戶裝置資訊或當前頁面的 URL 相關數據。以下提供三個經典的 JavaScript 代碼片段,分別用於取得螢幕解析度、完整網址與查詢字串參數。
<script>
document.write("寬為 " + screen.width + " 高為 " + screen.height);
</script>
透過 screen.width 與 screen.height 屬性即可獲取用戶螢幕的寬高(單位:像素)。注意屬性名稱區分大小寫,標準寫法為小寫。
<script>
document.write(self.location);
</script>
self.location(或 window.location.href)回傳當前視窗的完整 URL,包含協議、域名、路徑與查詢字串。
<script>
var add = top.location;
add = add.toString();
document.write(add.substring(add.indexOf("?") + 1, add.length));
</script>
步驟:
1. 獲取頂層視窗的 location 物件。
2. 轉為字串。
3. 使用 indexOf("?") 找到問號位置,再用 substring 擷取其後內容。
現代寫法建議: 直接使用 window.location.search 取得包含問號的查詢字串,或搭配 URLSearchParams 解析參數物件。