0

It's possible with

$('#iframe_id').contents().find('.stuff_to_modify).addClass('whatever');

But it's also possible using window.postMessage events, by sending a do_something message to a script from the iframe, which does the modifications when the message is received (adds that class).

I was wondering which is the way I should go, and what are the differences between these two methods (drawbacks, advantages).

The jQuery method seems nicer because I don't need to include any script in my iframe anymore

Alex
  • 60,472
  • 154
  • 401
  • 592

1 Answers1

3

The major difference between window.postMessage and jQuery sample you gave is that, postMessage enables cross-origin communication.

Meaning, if a Parent page which hosts the iframe is from domain A, while the content of the iframe is from domain B, then postMessage allows you to communicate while the jQuery approach will result in the security error.

The link you provided is a java script wrapper to window.postMessage implementation of the browser and falls back to window location hash polling for browsers that do not support it. Other benefits are listed in your link itself.

So, if the two pages are from same origin, i.e served from same domain, then you can go the jQuery approach itself. If it is from two different origins, you may have to use the JS wrapper.

Ramesh
  • 12,212
  • 2
  • 48
  • 83
  • what if the parent document has https and iframe doesn't, will it still work? – Alex Jun 11 '12 at 11:27
  • @Alex protocol, port, and host should be same to treat two pages are from same domain. So, if one is http and other is https, you may have to go with window.postMessage as it is treated as cross-origin. I would suggest you test this scenario also. – Ramesh Jun 11 '12 at 16:49