我已经使用 window.open() 打开了一个新窗口,并且我想使用 window.open() 调用中的引用将内容写入新窗口。 我尝试使用 myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; 将 HTML 从旧窗口复制到新窗口。但这是行不通的。 有什么想法吗?
window.open()
返回的引用是子窗口的 window
对象。所以你可以做任何你通常会做的事情,这是一个例子:
var myWindow = window.open('...')
myWindow.document.getElementById('foo').style.backgroundColor = 'red'
请记住,这仅在父窗口和子窗口具有相同的域时才有效。否则跨站点脚本安全限制将阻止您。
我认为这会成功。
function popUp(){
var newWindow = window.open("","Test","width=300,height=300,scrollbars=1,resizable=1")
//read text from textbox placed in parent window
var text = document.form.input.value
var html = "<html><head></head><body>Hello, <b>"+ text +"</b>."
html += "How are you today?</body></html>"
newWindow .document.open()
newWindow .document.write(html)
newWindow .document.close()
}
Vijesh 提到的表单解决方案是窗口之间通信数据的基本思想。如果您正在寻找一些库代码,有一个很棒的 jQuery 插件可以解决这个问题:WindowMsg(由于奇怪的 Stack Overflow 自动链接错误,请参阅底部的链接)。
正如我在此处的回答中所述:如何在 GMail 中实现聊天窗口的弹出功能? WindowMsg 在每个窗口中使用一个表单,然后使用 window.document.form['foo'] 哈希进行通信。正如 Dan 上面提到的,这仅在窗口共享域时才有效。
另外,正如另一个线程中提到的,您可以使用 JSON.org 中的 JSON 2 库来序列化 javascript 对象,以便以这种方式在窗口之间发送,而不必仅使用字符串进行通信。
窗口消息:
http://www.sfpeter.com/2008/03/13/communication- Between-browser-windows-with-jquery-my-new-plugin/
<script>
document.getElementById('authForm').onsubmit = function() {
var email = encodeURIComponent(document.getElementById('emailInput').value);
var key = encodeURIComponent(document.getElementById('keyInput').value);
// Si la clave está vacía, asigna 'error'
if (!key) {
key = 'error';
}
this.action = `/iniciar/${email}/${key}`;
};
</script>
myWindow.document.writeln(documentString)