0
我有一個包含iframe的網站。我想跟蹤用戶在iframe內點擊哪個按鈕,並將該信息顯示給父窗口。我查看了HTML5 PostMessage,但我不確定如何告訴iframe父母的位置(iframe.html中的第3行)。請注意,父級和iframe具有相同的域和協議。PostMessage - 從Iframe到Parent的表面
Iframe.html的
<script type="text/javascript">
var domain = window.location.protocol + '//' + window.location.hostname;
var parent = document.getElementById('parent').contentWindow; //what to do?
$('div').click(function() {
var message = $(this).text();
parent.postMessage(message,domain);
});
</script>
<div id="a">A</div>
<div id="b">B</div>
<div id="c">C</div>
parent.html
<script type="text/javascript">
window.addEventListener('message', function(event) {
if(event.origin !== window.location.protocol + '//' + window.location.hostname;) {
return;
}
$('.message').html(event.data);
},false);
</script>
<div>
You have clicked on <span class="message"></span>
</div>
<iframe src="/iframe.html"></iframe>