Apply "onclick" to all iFrame elements

How to use DOM JavaScript to apply events onclickto links inside iframe?

Here is what I'm trying to not work:

document.getElementById('myIframe').contentDocument.getElementsByTagName('a').onclick = function();

No errors seem to be thrown, and I have full control of the material in iframe.

Here is what code to check and see if I can even calculate how many are divin mine iframe.

// access body
var docBody = document.getElementsByTagName("body")[0];

// create and load iframe element
var embed_results = document.createElement('iframe');
embed_results.id = "myIframe";
embed_results.setAttribute("src", "http://www.mysite.com/syndication/php/embed.php");

// append to body
docBody.appendChild(embed_results);

// count the divs in iframe and alert   
alert(document.getElementById("myIframe").contentDocument.getElementsByTagName('div').length);
-1
source share
2 answers

Perhaps iFrame may host content from another site in another domain.

The ability to access content in other domains would constitute a security vulnerability for the user, and therefore this cannot be done using Javascript.

iFrame.

+7

getElementsByTagName NodeCollection, onclick node . .

var links = document.getElementById('myIframe').contentDocument.getElementsByTagName('a');
for(var i=0;i<links.length;++i)links[i].onclick=function(){}

,

embed_results.onload=function(){
   // your code
}
+3

Source: https://habr.com/ru/post/1725665/


All Articles