0

I am trying to highlight text which is inside of an iframe.

Outside of an iframe, it works perfectly:

$('p').highlight('text');

To highlight text within an iframe, I used the following code but it doesn't work:

$( 'iframe' ).contents().find('html').highlight('domain');

https://jsfiddle.net/1tvsj8ho/

On jsfiddle you may get an error (Blocked a frame with origin) but to me that's not important, since I am using a local file.

Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338

1 Answers1

0

Assuming the files are on the same domain at a real (non-file://) URL, so you have no CORS restrictions to worry about, you should be able to do this by waiting for the iframe's load event to fire before calling your highlight function:

$(function() { // document ready for parent window
  // highlight in the parent:
  $('p').highlight('text');

  // highlight inside iframe...
  $('iframe').on('load', function() { // ...when it's ready
    $(this).contents().find('p').highlight('text')
  });
});

(It's unfortunately difficult to demonstrate this in a snippet, due to those very same CORS restrictions, but I've tested this on my own localhost and it does work provided the highlight() function is defined in the parent window.)

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53