location 物件包含目前網址的協定、主機、路徑、查詢字串等資訊。若要取得根路徑,可從 pathname 取出第一段目錄,再與 protocol 和 host 組合成完整路徑。
以下函式可取得目前網站的根路徑。
function getBasePath() {
var obj = window.location;
var contextPath = obj.pathname.split('/')[1];
return obj.protocol + '//' + obj.host + '/' + contextPath;
}常見 location 屬性包括 href、host、hostname、pathname、port、protocol 與 search。