三個輸入框:收件人 i_rescive、抄送 i_cc、密送 i_bcc。點擊對應「添加」按鈕,彈窗選取聯絡人後,將 Email 填入對應輸入框。
按鈕 id="btn_rescive" → 輸入框 id="i_rescive",以 btn_ / i_ 前綴對應。
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>聯絡人填入示範</title><style>
textarea { width:300px; height:60px; display:block; margin:4px 0; }
button { margin:2px; }
</style></head><body>
<h3>主視窗</h3>
<textarea id="i_rescive" placeholder="收件人"></textarea>
<button id="btn_rescive" onclick="openPicker(this)">添加收件人</button>
<br>
<textarea id="i_cc" placeholder="抄送"></textarea>
<button id="btn_cc" onclick="openPicker(this)">添加抄送</button>
<br>
<textarea id="i_bcc" placeholder="密送"></textarea>
<button id="btn_bcc" onclick="openPicker(this)">添加密送</button>
<script>
function openPicker(btn) {
// 實際專案:window.open('selectUser.jsp', 'picker', 'width=400,height=500');
// 這裡模擬 picker 回傳
const emails = prompt('輸入 Email,分號分隔:', 'a@x.com;b@y.com');
if (!emails) return;
// 依按鈕 ID 推導目標輸入框 ID
const targetId = 'i_' + btn.id.slice(4); // 去掉 "btn_"
document.getElementById(targetId).value += emails + ';';
}
</script>
</body></html>
<!-- picker.jsp / selectUser.jsp -->
<script>
function confirmSelection() {
const selected = [...document.querySelectorAll('[name=cbUserName]:checked')]
.map(cb => cb.value + '@domain.com')
.join(';');
if (!selected) { alert('請選擇聯絡人'); return; }
// 寫入 opener 視窗對應輸入框
// 假設 opener 已開啟時帶入 targetId 參數,或由 opener 傳遞 callback
// 簡單做法:opener 視窗定義全域函數 receiveEmails(targetId, emails)
if (window.opener && window.opener.receiveEmails) {
window.opener.receiveEmails(window.opener._currentTargetId, selected);
}
window.close();
}
</script>
// 主視窗
let _currentTargetId = null;
function openPicker(btn) {
_currentTargetId = 'i_' + btn.id.slice(4);
window.open('picker.jsp', 'picker', 'width=400,height=500');
}
function receiveEmails(targetId, emails) {
document.getElementById(targetId).value += emails + ';';
}
// 主視窗
window.addEventListener('message', e => {
if (e.origin !== 'https://your-domain.com') return;
if (e.data.type === 'emails') {
document.getElementById(e.data.targetId).value += e.data.emails + ';';
}
});
// 彈窗
window.opener.postMessage({type:'emails', targetId:_currentTargetId, emails:selected}, 'https://your-domain.com');
btn_* ↔ i_*,單一 handler 通用。window.opener 直接呼叫;跨域用 postMessage。_currentTargetId。<%=basePath%> 等需確保正確編碼,防 XSS。