在純前端場景下要拿到應用部署的上下文路徑(context path),不必依賴後端注入的 EL 表達式,直接從 document.location.href 逐層切出來就行。
// 取得 web 應用上下文路徑
var webroot = document.location.href;
webroot = webroot.substring(webroot.indexOf('//') + 2, webroot.length); // 去掉 https://
webroot = webroot.substring(webroot.indexOf('/') + 1, webroot.length); // 去掉網域
webroot = webroot.substring(0, webroot.indexOf('/')); // 留下第一層目錄
var rootpath = "/" + webroot;
三步驟分別對應「去掉協定」「去掉主機名稱」「取第一段路徑」,最後補上斜線就是可用的根路徑,例如 /myapp。
如果專案允許,其實有更省事的選擇:location.pathname.split('/')[1] 一行就能拿到同樣結果。不過上面這種寫法的優點是不依賴 pathname 格式,且在拼接靜資源位址、跳轉後端介面時語意比較明確。真正要注意的是,如果應用部署在根路徑下(也就是網址直接是 https://host/index.html),這段邏輯會取到 index.html,實作時需要多加一個判斷分支。