Javascript中要實(shí)現(xiàn)跨域通信,主要有window.name,jsonp,document.domain,cors等方法。不過在H5中有一種新的方法postMessage可以安全實(shí)現(xiàn)跨域通信,并且使用簡(jiǎn)單。

要使用postMessage,首先得檢查瀏覽器是否支持該方法,postMessage屬于window對(duì)象,檢測(cè)方法如下:

if('postMessage' in window){
    
}else{
    console.log('瀏覽器不支持postMessage');
}

postMessage使用語(yǔ)法如下所示。

復(fù)制代碼
otherWindow.postMessage(message, targetOrigin, [transfer]);

otherWindow必須是一個(gè)window對(duì)象的引用,如iframe的contentWindow,window.open的返回對(duì)象,window.frames[index]等。

targetOrigin指定otherWindow的源,如果目標(biāo)窗口的協(xié)議,主機(jī)地址,端口只要一個(gè)不同,該方法便不會(huì)執(zhí)行信息發(fā)送
復(fù)制代碼

為了能接收到postMessage發(fā)送的消息,必須在window對(duì)象上監(jiān)聽message事件,該事件對(duì)象包涵了data(消息)、origin(來源地址)、source(來源窗口代理)等屬性,使用如下所示