window.open(url, '_blank') 預設發送 GET 請求,URL 長度受限且參數暴露在網址列。需求:在新視窗以 POST 方式提交表單資料,隱藏敏感參數。
function openPostWindow(url, targetName, data) {
const form = document.createElement('form');
form.method = 'POST';
form.action = url;
form.target = targetName || '_blank';
form.style.display = 'none';
for (const [key, value] of Object.entries(data)) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = value;
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
// 使用
openPostWindow('/target.action', 'newWindow', {
xtid: 'sys001',
xtmc: '子系統一'
});
優點:全瀏覽器支援、無需後端配合、參數不顯示在 URL。
缺點:無法攜帶自定義 Header、無法獲取響應內容(新視窗獨立載入)。
async function openWithAjax(url, data) {
try {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const html = await res.text(); // 假設後端返回完整 HTML
const win = window.open('', '_blank');
win.document.write(html);
win.document.close();
} catch (err) {
console.error(err);
alert('請求失敗');
}
}
注意:瀏覽器可能攔截 window.open,需由用戶手勢(click)觸發。
target="_blank" 的真實表單(無 JS 也可工作)<form action="/target.action" method="POST" target="_blank">
<input type="hidden" name="xtid" value="sys001">
<input type="hidden" name="xtmc" value="子系統一">
<button type="submit">在新視窗打開</button>
</form>
最簡單、語義化、無障礙友好,強烈推薦靜態頁面場景使用。
navigator.sendBeacon(僅發送,不關心響應)const blob = new Blob([new URLSearchParams(data).toString()], { type: 'application/x-www-form-urlencoded' });
navigator.sendBeacon(url, blob);
// 但無法指定 target="_blank",新視窗需另行開啟空白頁
Access-Control-Allow-Origin(若為 AJAX)或接受無 CORS 的表單提交。window.opener 通訊;跨源則需 postMessage。