Skip to content Skip to sidebar Skip to footer

Set Iframe Url Based On Dynamic Url

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

Solution 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 :(


Solution 2:

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.


Solution 3:

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='#'>

Post a Comment for "Set Iframe Url Based On Dynamic Url"