父頁面 ParentForm.aspx 開啟子頁面 SubForm.aspx,子頁面關閉時將文字方塊值回寫父頁面。
<script type="text/javascript">
function OpenSubForm(targetControlId) {
var url = "SubForm.aspx?Ret_Form=form1&Ret_Value=" + targetControlId;
var opts = "height=500,width=500,top=30,left=30,dependent=yes,location=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no";
window.open(url, 'subForm', opts).focus();
return false;
}
</script>
<asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="開啟子視窗" OnClientClick="return OpenSubForm('TextBox1');" />
protected void btnClose_Click(object sender, EventArgs e)
{
string retForm = Request.QueryString["Ret_Form"] ?? "document.forms[0]";
string retControl = Request.QueryString["Ret_Value"];
string script = $@"
<script type='text/javascript'>
window.opener.{retForm}.{retControl}.value = '{txtValue.Text.Replace("'", "\\'")}';
window.close();
</script>";
Response.Write(script);
}
value.Replace("'", "\\'").Replace("\n", "\\n").Replace("\r", "\\r")。Ret_Form、Ret_Value 符合預期格式,防止 XSS。postMessage 跨文件通訊,不依賴 window.opener (可能被瀏覽器封鎖)。// 子頁面
window.opener.postMessage({ controlId: "TextBox1", value: "使用者輸入" }, "*");
// 父頁面
window.addEventListener("message", e => {
if (e.origin !== location.origin) return; // 驗證來源
var ctrl = document.getElementById(e.data.controlId);
if (ctrl) ctrl.value = e.data.value;
});