JavaScript: Detection of a link click inside an iframe

Paul picture Paul · Dec 10, 2010 · Viewed 8.7k times · Source

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

Answer

Tim Down picture Tim Down · Dec 10, 2010

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);
}