0

Does anybody know a javascript code that will detect the dynamic url of the page (?q=Chicken) and set the url of the iframe on the page to https://www.google.co.uk/?#q=Chicken. (I am not actually making a google search client!)

    Get - Text added to Url
    set
    Url of iframe to https://www.google.co.uk/?#q=Chicken

This will all be onload.

JBithell
  • 627
  • 2
  • 11
  • 27

3 Answers3

1

Try this , URL browsed "http://something.com/index.asp?search=anything

  <script type="text/javascript">

    $( document ).ready(function()
    {

    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

     var urliframe =  "http://www.google.co.uk/?#q="+getParameterByName('search');

     $('#myIframe').attr('href',urliframe);

    });

    </script>

    <iframe id='myIframe' href='#'>
Dimag Kharab
  • 4,439
  • 1
  • 24
  • 45
1

You can use location.search in Javascript. https://developer.mozilla.org/en-US/docs/Web/API/URLUtils.search

So an example would be:

$('iframe')[0].src = "http://www.google.co.uk/" + location.search;

But, Google doesn't like to be in an iframe. You should try another site.

T.S.
  • 1,242
  • 13
  • 22
1

You need something like this:

<script>
function get_url_parameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}

document.addEventListener('DOMContentLoaded', doc_loaded, false);
function doc_loaded() {
    //var url = 'https://www.google.co.uk/?#q=' + get_url_parameter('q');
    var url = 'http://example.com/?#q=' + get_url_parameter('q');
    document.getElementById('iframe_id').src = url;
}
</script>
<iframe src="#" id="iframe_id" width="1000" height="500"></iframe>

but it will not work for Google because it's sending an "X-Frame-Options: SAMEORIGIN" response header :(

Samuil Banti
  • 1,735
  • 1
  • 15
  • 26
  • Worked perfectly for me. Thanks very much! – JBithell Mar 14 '14 at 18:40
  • Is there any way to set the iframe to a different url if there is nothing added to the page's url? (If it is null set it to google homepage for example) – JBithell Mar 14 '14 at 19:09
  • 1
    You could do something like this: if(get_url_parameter('q') == null) { var url = 'http://the-url-that-you-need/'; } else { var url = 'http://example.com/?#q=' + get_url_parameter('q'); } – Samuil Banti Mar 17 '14 at 13:31