简体   繁体   中英

Highlight text within an iframe

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.

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM