tags:

views:

2638

answers:

2

How do I use the JavaScript DOM to apply onclick events to links inside of an iframe?

Here's what I'm trying that isn't working:

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

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

Here is some code to test and see if I can at least count how many div's are in my 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);
+6  A: 

It is possible for an iFrame to source content from another website on a different domain.

Being able to access content on other domains would represent a security vulnerability to the user and so it is not possible to do this via Javascript.

For this reason, you can not attach events in your page to content within an iFrame.

Jon Winstanley
It is possible if you control the iframe on both domains - http://softwareas.com/cross-domain-communication-with-iframes
Tony
+2  A: 

getElementsByTagName returns a NodeCollection, so you have to iterate throgh this collection and add onclick handler to every node in that collection. The code below should work.

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

also make sure, you run this code after the frames' content is loaded

embed_results.onload=function(){
   // your code
}
Rafael
hmm, got a "permission denied error
johnnietheblack
As Jon already answered, JavaScript security policy doesn't allow the browser to access or modify page contents from other domain.
Rafael