Tutorial :Accessing an element in a frame using a jQuery reference to the frame



Question:

I have a frame that's nested in an iFrame. <iframe>..<frameset..><frame id="report">. I have a jQuery reference, myFrame, to the report frame. I don't have control to the html. I am trying to modify an element in the frame. contents() doesn't work with frames. I tried using a context like myFrame.document & myFrame.contentDocument but they give errors.

How do I reference the frame's document or content using jQuery? Is a jQuery reference different than a javascript reference?

ADDITION:

EVERYTHING IS IN THE SAME DOMAIN. I know about the browser's cross domain security block.

ADDITION2:

I had some html code in my original question and didn't notice they got hidden.


Solution:1

Is your frame that's inside your frame on the same domain as the container of the frame? You should know by now if they aren't on the same domain you can't manipulate it due to security limitations by the browser.

Is a jQuery reference different than a javascript reference?

jQuery IS Javascript, it does a lot of branching under the core so you don't have to do a lot of the dirty work.

Edit: Since no code was provided... had to make a demo myself.

http://medero.org/frame.html

$('iframe').contents().find('frame').get(0).contentWindow.document  

Didn't test in IE.

For clarification...

  • $('#el') returns a jQuery object.
  • $('#el').get(0) returns the first element in the jQuery array-like object, a reference to the real DOM element.


Solution:2

Yo dawg...The browser security model will prevent any DOM access to an iFrame from a different domain. This is to prevent somebody embedding a page and them sabotaging the content/layout, capturing form data and so on.

If you have access to the source of the iFramed page you can (via a third iFrame on the same domain as the browser viewport) send information to the top page via url parameters. Otherwise you're out of luck.

There isn't much point doing this if you just want to change the layout of the page since you'll have css access anyway. But it is useful for setting the height of the iFrame to whatever the scroll height of the iFrame is.

Edit I think this is what you were looking for: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/

$('#iframeID').contents().find('#someID').html();  


Solution:3

This is the selector:

$(top.window.frames['frameID'][1].document).contents()[0].find('elementinFrame')  

Although it doesn't work every single time and I am still find out why.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »