Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Detection of a link click inside an iframe

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

like image 466
Paul Avatar asked Dec 10 '10 15:12

Paul


People also ask

How do I capture a click event in iframe?

Answer: Use the jQuery contents() method If you try to detect or capture a click event inside an iframe simply using jQuery click() method it will not work, because iframe embed a web page within another web page. However, you can still do it on the same domain utilizing the jQuery contents() and load() method.

How do I find if a click event on a cross domain iframe?

you can always detect the click on a div using the onclick event without caring what is inside the div . but you can check if the div innerHTML to see if the ad is loaded or it's empty and if the ad was loaded then run your script.

Can I get element inside iframe?

Getting the element in IframegetElementById() method by passing iframe id as an argument. const iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe.

Can Javascript access DOM of iframe?

yes. getElementsByTagName('iframe') to refer to a nodeList and access elements inside with [0], assuming you're dealing with one. or you can do a loop.


2 Answers

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);
}
like image 116
Tim Down Avatar answered Nov 16 '22 08:11

Tim Down


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");
});
like image 29
Anton Avatar answered Nov 16 '22 07:11

Anton