Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass value to iframe from a window

I need to send a value to an iframe.

The iframe is present within the current window. How can I achieve this?

I need to do it with javascript in the parent window that contains the iframe.

like image 711
praveenjayapal Avatar asked Feb 11 '09 12:02

praveenjayapal


People also ask

Can you pass data into an iframe?

The usual solution is to use window. parent in the frame to get "up" (into the document which contains the iframe tag). Now you can call any method in the container document. This method can manipulate the frame (for example call some JavaScript in the frame with the parameters you need).

Is it bad practice to use iframe?

Iframes Bring Security Risks. If you create an iframe, your site becomes vulnerable to cross-site attacks. You may get a submittable malicious web form, phishing your users' personal data. A malicious user can run a plug-in.

Can you iframe a specific part of page?

Set the iframe to the appropriate width and height and set the scrolling attribute to "no". If the area you want is not in the top-left portion of the page, you can scroll the content to the appropriate area.


1 Answers

First, you need to understand that you have two documents: The frame and the container (which contains the frame).

The main obstacle with manipulating the frame from the container is that the frame loads asynchronously. You can't simply access it any time, you must know when it has finished loading. So you need a trick. The usual solution is to use window.parent in the frame to get "up" (into the document which contains the iframe tag).

Now you can call any method in the container document. This method can manipulate the frame (for example call some JavaScript in the frame with the parameters you need). To know when to call the method, you have two options:

  1. Call it from body.onload of the frame.

  2. Put a script element as the last thing into the HTML content of the frame where you call the method of the container (left as an exercise for the reader).

So the frame looks like this:

<script> function init() { window.parent.setUpFrame(); return true; } function yourMethod(arg) { ... } </script> <body onload="init();">...</body> 

And the container like this:

<script> function setUpFrame() {      var frame = window.frames['frame-id'].contentWindow;     frame.yourMethod('hello'); } </script> <body><iframe name="frame-id" src="..."></iframe></body> 
like image 188
Aaron Digulla Avatar answered Oct 14 '22 02:10

Aaron Digulla