DIV CSS 佈局教程網

兩種取得當前網域名稱的 JavaScript 寫法
編輯:JavaScript綜合知識     

取得目前頁面的網域,JavaScript 提供了不止一種途徑。最常用的是 window.location.host 與 document.domain。

基本用法

// 取得當前網域
var host1 = window.location.host;
var host2 = document.domain;

// 取得當前頁面完整網址
var url = window.location.href;

實際示範

<script>
// 取得網域
var host  = window.location.host;
var host2 = document.domain;

// 取得頁面完整網址
var url = window.location.href;

document.write("<br>host  =" + host);
document.write("<br>host2 =" + host2);
document.write("<br>url   =" + url);
</script>

兩者的差別

window.location.host 包含主機名稱與連接埠(若有),例如 example.com:8080;document.domain 則只有主機名稱,不含連接埠。如果只需要純網域,兩者都能勝任,但要注意 document.domain 可以被程式碼「放寬」到父網域(例如從 www.example.com 設為 example.com)以實現跨子網域溝通,這個特性在今日已因安全考量而不建議使用。

補充:location 物件的常用成員

thisTLoc  = top.location.href;        // 最上層視窗的網址
thisPLoc  = parent.document.location; // 父視窗的網址
thisTHost = top.location.hostname;    // 最上層視窗的主機名
thisHost  = location.hostname;        // 目前視窗的主機名

var strwrite  = " thisTLoc: [" + thisTLoc  + "]";
strwrite += " thisPLoc: [" + thisPLoc  + "]";
strwrite += " thisTHost: [" + thisTHost + "]";
strwrite += " thisHost: [" + thisHost  + "]";
document.write(strwrite);

這段程式常被用在廣告或統計腳本裡,用來確認自己被嵌在哪一層頁面中。

location 家族快速對照

location.href     完整網址
location.host     主機名稱 + 連接埠
location.hostname 只有主機名稱
location.port     連接埠
location.pathname 路徑
location.protocol 協定(http: / https:)
location.search   查詢字串(含 ?)
location.hash     錨點(含 #)

實務上最實用的是 location.origin,它直接給出「協定 + 主機 + 連接埠」,是組裝絕對網址時最方便的起點。跨 iframe 存取 top.location 時也要留意同源政策——若父頁面與目前頁面不同源,讀取會直接丟出安全性錯誤,需要改用 postMessage 溝通。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved