JavaScript: Detection of a link click inside an iframe

两盒软妹~` 提交于 2019-12-07 02:32:31

问题


How to detect user's click on the link inside the iframe using JavaScript?


回答1:


You are able to check iframe load event

onLoad="alert(this.contentWindow.location);"

or on jquery:

$('iframe#yourId').load(function() {
  alert("the iframe has been loaded");
});



回答2:


Assuming you have an iframe with ID "myIframe", and the iframe comes from the same domain as the main document, the following will detect a click anywhere in the document. This will also work when the document is editable, which using the document's onclick property would not:

function iframeClickHandler() {
    alert("Iframe clicked");
}

var iframe = document.getElementById("myIframe");
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

if (typeof iframeDoc.addEventListener != "undefined") {
    iframeDoc.addEventListener("click", iframeClickHandler, false);
} else if (typeof iframeDoc.attachEvent != "undefined") {
    iframeDoc.attachEvent ("onclick", iframeClickHandler);
}


来源:https://stackoverflow.com/questions/4410183/javascript-detection-of-a-link-click-inside-an-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!