简体   繁体   中英

Grab url variable from inside an iframe

I have no control over anything apart from the iframe.

my form sits in the iframe and I want to grab a variable that comes from the parent link.

Not sure if its poss as the parent url is a different domain.

I cant give live urls, but for example:

www.theredomain.com?ref=variable is the parent url

I need to grab the variable of 'ref' from my iframe which is on a different domain. I have tried the below but it didnt seem to do anything.

<script language="javascript">
function getUrlVars() {
var vars = {};
var parts = window.parent.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    vars[key] = value;
});
return vars;
}
var first = getUrlVars()["ref"];
alert(first);
</script>

如果iframe在另一个域中,则无法访问该iframe。

One way of sending data between two iframes that are not on the same domain and if you have access to both of these to extend them is to use postMessage

it is fairly straight forward. On one side you implement a bit of js as an event listener which recognises the url it is coming from, on the other, you use the .postMessage method to send to that parent iframe. Check the browser support as well if it applies to you.

Thanks for the input guys - finally resolved it. I used the below function to break out the variable from the referrer url

    <script>  
      function getUrlVars() {
    var vars = {};
    var parts = document.referrer.replace(/[?&]+([^=&]+)=([^&]*)/gi, function    (m,key,value)   {
    vars[key] = value;
      });
    return vars;
      }
     </script>

Then put it into my form like

    <script>
        $("#submit").click(function() {
       var first = getUrlVars()["ref"];
        $(".referer").val(first);
        }); 
    <script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM