0

是否可以检测在 iframe 中单击了哪个元素?

var iframe = document.getElementById("my_iframe");
	iframe.document.addEventListener('click', function(event) {		
		console.log(this.id);
	}, false);
<iframe id="my_iframe"
        src="https://fr.wikipedia.org/wiki/Wiki"
        frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px"
         height="100%" width="100%">
</iframe>

4

1 回答 1

1

您需要.contentWindow.document在 iframe 上使用:

var iframe = document.getElementById("my_iframe");
iframe.contentWindow.document.addEventListener('click', function(event) {		
	console.log(this.id);
}, false);
<iframe id="my_iframe"
        src="https://fr.wikipedia.org/wiki/Wiki"
        frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px"
         height="100%" width="100%">
</iframe>

请注意,您仍然需要处理讨厌的跨域问题。(如果该 iframe 的来源与您当前访问的网站不同,您将无法看到任何元素,或访问该 iframe 中的几乎任何内容)。

但是,如果您可以访问这两个站点,则可以与 postmessage API 进行通信:https ://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

于 2018-10-19T15:15:22.990 回答