取得當前頁面網址有非常多種寫法,差別在於要的是「誰的」網址,以及取到的是哪一段。以下把瀏覽器端與後端(JSP)的做法並列整理。
<script type="text/javascript">
thisURL = document.URL;
thisHREF = document.location.href;
thisSLoc = self.location.href;
thisDLoc = document.location;
strwrite = " thisURL: [" + thisURL + "]<br />";
strwrite += " thisHREF: [" + thisHREF + "]<br />";
strwrite += " thisSLoc: [" + thisSLoc + "]<br />";
strwrite += " thisDLoc: [" + thisDLoc + "]<br />";
document.write(strwrite);
這四個寫法在一般情況下結果相同,但來源不同:document.URL 是文件物件的屬性,而 location 系列則透過 window 階層取得。self 是 window 的別名,document.location 則是文件物件上的 location 參照。
thisTLoc = top.location.href; // 最上層視窗
thisPLoc = parent.document.location; // 直接父視窗
thisTHost = top.location.hostname; // 最上層視窗的主機名
thisHost = location.hostname; // 目前視窗的主機名
strwrite = " thisTLoc: [" + thisTLoc + "]<br />";
strwrite += " thisPLoc: [" + thisPLoc + "]<br />";
strwrite += " thisTHost: [" + thisTHost + "]<br />";
strwrite += " thisHost: [" + thisHost + "]<br />";
document.write(strwrite);
在 iframe 或 frameset 環境中,top 與 parent 的層級差異就很重要了。要注意跨域的情況下讀取 top.location 會因同源策略而拋出錯誤。
tmpHPage = thisHREF.split("/");
thisHPage = tmpHPage[tmpHPage.length - 1];
tmpUPage = thisURL.split("/");
thisUPage = tmpUPage[tmpUPage.length - 1];
strwrite = " thisHPage: [" + thisHPage + "]<br />";
strwrite += " thisUPage: [" + thisUPage + "]<br />";
document.write(strwrite);
以斜線切開後取最後一段,就得到檔名。這個技巧至今仍常用,但要注意若網址結尾帶斜線,取到的會是空字串。
var url = "<%=request.getRequestURI()%>";
alert(url);
JSP 提供的相關方法:
request.getRequestURI():請求的 URI,不含協定與網域。request.getRequestURL():完整的 URL,含協定、網域與連接埠。request.getQueryString():查詢字串部分。request.getServletPath():Servlet 的路徑部分。request.getScheme() + "://" + request.getServerName() + ":"
+ request.getServerPort() + request.getRequestURI()
把協定、主機名稱、連接埠與 URI 四段拼起來,就得到一个不依賴 proxy 設定的完整網址。相比直接用 getRequestURL(),這種拼法在連接埠需要明確指定的場景下更可控。