在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/HTML/ 使用postmessage報(bào)錯(cuò),F(xiàn)ailed to execute 'postM

使用postmessage報(bào)錯(cuò),F(xiàn)ailed to execute 'postMessage' on 'DOMWindow'

使用postMessage發(fā)送跨域消息,
window.postMessage('hello there!', location.protocol + '//a.b.com');

但是報(bào)了下面的錯(cuò)誤:

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://a.b.com') does not match the recipient window's origin ('http://c.e.com')

請(qǐng)問(wèn)是什么原因?

回答
編輯回答
綰青絲

otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow:其他窗口的一個(gè)引用,比如iframe的contentWindow屬性、執(zhí)行window.open返回的窗口對(duì)象、或者是命名過(guò)或數(shù)值索引的window.frames。
otherWindow不能是當(dāng)前窗口哦
參見(jiàn)MDN

2017年7月7日 17:36
編輯回答
墨小白

使用event.source作為回信對(duì)象
具體參見(jiàn):https://developer.mozilla.org...

//當(dāng)A頁(yè)面postMessage被調(diào)用后,這個(gè)function被addEventListenner調(diào)用
function receiveMessage(event)
{
  // 我們能信任信息來(lái)源嗎?
  if (event.origin !== "http://example.com:8080")
    return;

  // event.source 就當(dāng)前彈出頁(yè)的來(lái)源頁(yè)面
  // event.data 是 "hello there!"

  // 假設(shè)你已經(jīng)驗(yàn)證了所受到信息的origin (任何時(shí)候你都應(yīng)該這樣做), 一個(gè)很方便的方式就是把enent.source
  // 作為回信的對(duì)象,并且把event.origin作為targetOrigin
  event.source.postMessage("hi there yourself!  the secret response " +
                           "is: rheeeeet!",
                           event.origin);
}

window.addEventListener("message", receiveMessage, false);
2018年8月9日 16:31