常見需求:主頁(add.jsp)點擊「請選擇」按鈕,彈出選擇頁(select.jsp)列出資料庫企業清單,使用者勾選一筆後確認,彈窗關閉並將企業名稱回填主頁輸入框。本文整理兩種主流實作方式。
window.showModalDialog(IE 專屬,不建議新專案)舊專案常用,但 Chrome/Firefox/Edge 已移除支援。程式碼如下:
// add.jsp
function openWindow() {
var result = window.showModalDialog('/xq.do?action=showTjList', window,
'status:no;scroll:yes;dialogWidth:400px;dialogHeight:400px');
if (result) {
document.getElementById('companyName').value = result.name;
document.getElementById('companyId').value = result.id;
}
}
// select.jsp 確認按鈕
function confirmSelect(id, name) {
window.returnValue = {id: id, name: name};
window.close();
}
缺點:非標準、跨瀏覽器相容性差、無法在現代瀏覽器使用。
window.open + postMessage(標準、跨域安全、推薦)function openSelectDialog() {
const dialog = window.open('/xq.do?action=showTjList', 'selectDialog', 'width=600,height=500');
window.addEventListener('message', function(event) {
if (event.origin !== location.origin) return; // 安全驗證
if (event.data.type === 'SELECT_COMPANY') {
document.getElementById('companyName').value = event.data.name;
document.getElementById('companyId').value = event.data.id;
dialog.close();
}
});
}
function confirmSelect(id, name) {
window.opener.postMessage({
type: 'SELECT_COMPANY',
id: id,
name: name
}, window.location.origin);
window.close();
}
select.jsp 載入時呼叫後端 Action 取得企業清單 JSON,前端渲染表格,勾選後帶回。Action 只需回傳 JSON,無需轉發 JSP。
/xq.do?action=showTjList:回傳企業清單 JSON(分頁、搜尋參數)。postMessage 即可。location.href)並利用 sessionStorage 暫存選擇結果返回。現代 Web 開發請捨棄 showModalDialog,採用 window.open + postMessage 或前端框架 Modal 組件,確保跨瀏覽器相容與安全性。