1

I am trying to check the css style of an element inside of an iframe but cannot seem to find the element.

It works fine if not inside the iframe so has to be with the way I am finding the content in the iframe.

Here is a jsFiddle

var iframe = document.createElement('iframe');
var html = '<body><div id="cadrage" style="color:black">Test</div></body>';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
document.body.appendChild(iframe);


$('iframe').ready( function() {
      if( $('iframe').contents().find("#cadrage").css('color') == "rgb(0, 0, 0)" ) {
        alert('It equal');
      } else {
        alert('It did not equal');
      }
});
Keith Power
  • 13,891
  • 22
  • 66
  • 135

1 Answers1

1

In a iframe with jquery, you should use load() instead of ready():

$('iframe').load( function() {

Working fiddle: http://jsfiddle.net/jpaulet/r1y2vrh4/9/

And it works fine! Hope it helps

JP. Aulet
  • 4,375
  • 4
  • 26
  • 39
  • I don't see that working when I'm testing .. It should alert() the good message no ? – Vincent G Apr 10 '16 at 16:43
  • I am not getting equal, is it not `ready()` with jQuery 1.8 and up? – Keith Power Apr 10 '16 at 16:46
  • It don't. I am getting this error in the logs : `Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://fiddle.jshell.net" from accessing a frame with origin "null". The frame requesting access has a protocol of "http", the frame being accessed has a protocol of "data". Protocols must match.` – Vincent G Apr 10 '16 at 16:47
  • 1: You are loading jquery 1.1 in the html (jquery/1.11.1/jquery.min.js). 2: My fiddle is not running for you?? When I access and run the code always returns me the desired alert value... And this is the proper way to do this, the iframe should be loaded in order to the content is already there. Here: https://www.dropbox.com/s/g3vchfs4iil51or/alert.png?dl=0 – JP. Aulet Apr 10 '16 at 16:50
  • It's working on Firefox, just tested it so I assume you're testing it on Firefox too. But on my version of Chrome, I get this error above. (Version 49.0.2623.110 m) – Vincent G Apr 10 '16 at 17:04
  • Check this out : http://stackoverflow.com/questions/20572734/load-event-not-firing-when-iframe-is-loaded-in-chrome – Vincent G Apr 10 '16 at 17:08