38

I have a html page in which I am setting the src for an iframe programmatically. How can I pass parameters through the iframe src and get them in the child html?

Below my code:

<iframe id="myIframe" src="" height="250px"  width="100%" scrolling="yes" frameborder="0"></iframe>

function myFunction(){
$('#myIframe').attr('src', "myIframeRequest.html"); 
}
Reporter
  • 3,897
  • 5
  • 33
  • 47
JavaLearner
  • 389
  • 1
  • 3
  • 8
  • 2
    Add `?parameters` to the address, then in iframe check the `location.search`. – Teemu Feb 03 '15 at 09:52
  • the iframe is in an iframe, is that correct ? if not then your jquery code will work on the iframe in the same page, just make sure that you wrap it in a ready function or put it at the bottom of the page just before the closing body tag – Billy Feb 03 '15 at 10:05
  • location.search works fine. Thanks Teemu – JavaLearner Feb 03 '15 at 11:06
  • I've described the process here https://alfilatov.com/posts/how-to-pass-data-between-iframe-and-parent-window/ and here https://alfilatov.com/posts/how-to-pass-file-into-an-iframe-and-convert-it-to-blob-for-further-ajax-request/ (for file transferring) – Alex Filatov Nov 07 '20 at 05:14

3 Answers3

49

On the main page simply pass parameters as follows

function myFunction(){
$('#myIframe').attr('src', "myIframeRequest.html?param1=value1&param2=value2"); 
} 

In Iframe

You can use a script to get the desired parameter value from parameters passed to page.

<script>
function getParamValue(paramName)
{
    var url = window.location.search.substring(1); //get rid of "?" in querystring
    var qArray = url.split('&'); //get key-value pairs
    for (var i = 0; i < qArray.length; i++) 
    {
        var pArr = qArray[i].split('='); //split key and value
        if (pArr[0] == paramName) 
            return pArr[1]; //return value
    }
}
</script>

Then you can fetch the value of desired parameter like this

var param1 = getParamValue('param1');
rasso
  • 2,131
  • 3
  • 21
  • 24
  • 2
    You may want to add `pArr[1] = decodeURI(pArr[1]) ` before `return pArr[1]` – Fabio Magarelli Mar 18 '20 at 15:29
  • 1
    This is okay if you don't mind reloading the page in the iframe every time you need to pass it some data. Not ideal if you just want to pass data without reloading the page. To avoid reloading the page, see this solution: https://stackoverflow.com/a/41594695/753632 – Johann Aug 27 '20 at 17:43
9

If you have slightly more control on your iframe sandbox, you can try postMessage API to communicate with message on events you desire to trigger.

Shobhit Sharma
  • 604
  • 1
  • 9
  • 18
0

you should make a serverside page like (myIframeRequest.php) php/jsp and get the parameter value in that page if it s an html page then parse the window.location.href through javascript and find the query/param

Deepak David
  • 145
  • 6