网友回复
在两个不同域名的网页之间传递消息和调用方法,可以使用跨域消息传递(Cross-origin communication)技术,其中最常用的是窗口.postMessage()方法。postMessage()方法允许不同来源的窗口进行受限通信,以实现跨域消息传递。
以下是使用postMessage()的一个基本示例: 假设有两个域名:domainA.com和domainB.com。 在domainA.com中的代码示例:<!DOCTYPE html> <html> <head> <title>Domain A</title> <script> function sendMessage() { var iframe = document.getElementById('iframeB'); var message = {data: 'Hello from Domain A'}; iframe.contentWindow.postMessage(JSON.stringify(message), 'https://domainB.com'); } </script> </head> <body> <h1>Domain A</h1> <buttonBfwOnclick="sendMessage()">Send Message to Domain B</button> <iframe id="iframeB" src="https://domainB.com" width="100%" height="300px"></iframe> </body> </html>在domainB.com中的代码示例:
<!DOCTYPE html> <html> <head> <title>Domain B</title> <script> function receiveMessage(event) { if (event.origin !== 'https://domainA.com') return; var message = JSON.parse(event.data); console.log('Received message:', message.data); } window.addEventListener('message', receiveMessage, false); </script> </head> <body> <h1>Domain B</h1> </body> </html>在这个示例中,domainA.com中的sendMessage()函数将消息发送到domainB.com中的iframe。在domainB.com中,我们使用window.addEventListener()监听message事件,当domainB.com收到消息时,会触发receiveMessage函数。 请注意,为了安全起见,接收消息的页面需要检查event.origin属性,以确保消息是从期望的发送方发出的。这可以防止不受信任的第三方页面向您的页面发送消息。
这种方法适用于不同域名的网页之间的通信,包括父窗口与子iframe、两个相互独立的窗口或标签页等场景。
还可以让两个不同域名的网页同时连接共同的服务器,通过服务器来实现消息通讯交换。