[英]How to target an element outside an iframe with different protocol using Javascript postMessage
我在iframe中有一個按鈕,但我希望它觸發單擊后在iframe外部找到的另一個按鈕。
這是我一直在嘗試的一段代碼。
HTML
<body>
<iframe id="layer-frame" src="https://somepage.com">
<a href="https://page2.com" target="_blank" id="js-gopage2" class="js-iframepostmsg" alt="CLICK HERE TO Edit your profile">Edit your profile</a>
</iframe>
<div>
<a class="close" href="#">Close<span></span></a>
</div>
</body>
在父html中
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
if(event.data == "click!") {
$('a.close').trigger('click');
}
}
在iframe中
var targetOrigin = window.location.host;
top.window.postMessage("click!", targetOrigin);
targetOrigin = window.location.host
將為您提供從中發布頁面的主機名,但:
targetOrigin
指定要分派事件的otherWindow
的原點
和
otherWindow的文件的方案,主機名或端口不匹配所提供
targetOrigin
因此您需要提供一個完整的來源(例如http://example.com:234
),而不僅僅是主機名。
如果您不在乎允許讀取哪個來源,請使用"*"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.