Set iframe url based on dynamic Url

2019-08-27 20:29发布

问题:

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.

回答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 :(



回答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.



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