23

I would like to grab the parameters from a page that contains an iframe, and append the parameters to the src of the iframe.

Example:

PAGE CONTAINING IFRAME--

http://www.example.com/pref.html?c=%433r3jutlut9se%23&e=test%40example.com

IFRAME IN THE ABOVE PAGE--

<iframe id="myiframe" name="myiframe" src="prefcontent.aspx" frameborder="0"
width="100%" height="800"></iframe>

Here's one of the many things I've tried, which I thought would work in theory, but I had no luck with it:

<script language="javascript">
$(function() {

    var loc = window.location.toString(),
    params = loc.split('?')[1],
    params2 = loc.split('&')[2],
    iframe = $('#myiframe');

    console.log(params);

    iframe.src = iframe.src + '?' + params + '&' + params2;


});
</script>
pb2q
  • 58,613
  • 19
  • 146
  • 147
Nostalgia80
  • 493
  • 1
  • 5
  • 8
  • Is the point to just add the same querystring as the current page to the iframe source ? – adeneo Oct 17 '12 at 21:48
  • Yes, I just wanted to grab the same parameters from the parent page url and add them to the iframe src. Lededje's answer below works like a charm! Thank you for offering your help Adeneo! – Nostalgia80 Oct 18 '12 at 13:55

3 Answers3

17

if your using jQuery you might want to strip down your code up:

$(function() {
    var search = window.location.search;
    $("#myiframe").attr("src", $("#myiframe").attr("src")+search);
});

Use window.location.search; as it will snip off the hash tag at the end of the url and is a lot faster as it is native code.

Then use jQuery selectors to find and replace the attribute of src on the iframe, with it's current src plus the search acquired from this page.

Hope this helps.

lededje
  • 1,859
  • 1
  • 16
  • 25
  • 1
    YES!!!!! Thank you so very much lededje! I have been stuck on this for a long time. This helps immensely. :) – Nostalgia80 Oct 18 '12 at 13:31
  • This is a great solution! There is also a variant to encode all parameters in one and use decodeURIComponent, see http://stackoverflow.com/a/19553782/684229 – Tomas Mar 11 '14 at 12:26
14

You could append the querystring to the source of the iFrame

<script language="javascript">
    var iframe = document.getElementById('myiframe');
        iframe.src = iframe.src + window.location.search;
</script>
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

For the people who prefer a vanilla JavaScript solution without jQuery:

document.addEventListener('DOMContentLoaded', function () {
  const search = window.location.search;
  const myIframe = document.querySelector('#myiframe');
  myIframe.src = myIframe.src + search;
});
rozsazoltan
  • 2,831
  • 2
  • 7
  • 20