Wednesday, September 3, 2014

Submit form to an iframe

Sometimes there is a need to render an iframe. The content of the iframe may be fetched from a different web link by submitting a form. The example below shows the html and javascript to achieve that. Copy the below code in a file and name it as frame.html and open it in a browser. This will open this blog in an iframe. The example shows the how to do it with GET however the data can be fetched by making method as post in the form element.

 <meta charset="UTF-8"> 

<h1>Test for iframe submission</h1>

<!-- Define the iframe. -->
<iframe name="my_iframe" style="width: 100%; height: 300px"></iframe>

<!-- Define a form. 
     As we do not want to show the form elements, display:none is set.
     Also note the target set to iframe name     
<form method="get" id="my_form" action="" target="my_iframe" style="display:none">
    <!-- you can define more elements here -->

<!-- submit the form automatically so the frame will get rendered -->
<script type="text/javascript">


Clickjacking and X-Form-Options

If you are not able to render your page in the iframe than check that if the server hosting that page is not allowing to render that page. Many web applications do that to stop clickjacking attacks. This is done by using X-Form-Options. To see that replace the form element above with a pointer to 

<form method="get" id="my_form" action="" target="my_iframe" style="display:none">
    <input type="text" name="q" value""/>

On running it in Google chrome, you will see the following error in your browser console

Refused to display '' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

Google stops the search from rendering in an embedded iframe. You can see the details here .

X-Form-Options comes with three settings:
  • DENY - Deny in all situations
  • SAMEORIGIN - Allow only if it is coming from same url
  • ALLOW-FROM uri - Allow from the uri

No comments:

Post a Comment