25

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>
2
  • Is the point to just add the same querystring as the current page to the iframe source ? Commented Oct 17, 2012 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! Commented Oct 18, 2012 at 13:55

3 Answers 3

18

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.

Sign up to request clarification or add additional context in comments.

2 Comments

YES!!!!! Thank you so very much lededje! I have been stuck on this for a long time. This helps immensely. :)
This is a great solution! There is also a variant to encode all parameters in one and use decodeURIComponent, see stackoverflow.com/a/19553782/684229
17

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>

1 Comment

Perfect. Today I learned about window.location.search. Thanks.
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;
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.