2020-10-25 05:56:46
在 JavaScript 中打开新页面并进行交互,主要通过以下两种方法实现,并辅以特定的交互机制:
一、打开新页面的方法window.open()
语法:window.open(url, target, features)
url:要打开的页面地址。
target(可选):指定窗口名称(如 _blank),若同名窗口已存在则复用。
features(可选):定义窗口特性(如 width=500,height=300)。
示例:const newWindow = window.open('
target="_blank" 属性
适用于 <a> 标签或 <form>,直接在新标签页打开链接。
示例:<a href="
创建信道并传递端口给新窗口:const channel = new MessageChannel();const newWindow = window.open('child.html', '_blank');newWindow.onload = () => { newWindow.postMessage('init', '*', [channel.port2]);};channel.port1.onmessage = (e) => console.log('Received:', e.data);
子页面通过端口通信:// child.html 中window.addEventListener('message', (e) => { const port = e.ports[0]; port.postMessage('Port message received');});
父页面:
document.getElementById('openBtn').addEventListener('click', () => { const newWindow = window.open('child.html', '_blank'); newWindow.onload = () => { newWindow.postMessage({ type: 'greeting', text: 'Hello' }, '*'); };});子页面(child.html):
window.addEventListener('message', (e) => { if (e.data.type === 'greeting') { console.log('Received:', e.data.text); // 可回复消息 window.opener.postMessage('Hi parent!', '*'); }});通过上述方法,可灵活实现新页面的打开与跨窗口交互,兼顾功能性与安全性。