Jeff
Jeff

Reputation: 1017

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>

Upvotes: 0

Views: 193

Answers (3)

Jeff
Jeff

Reputation: 1017

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>

Upvotes: 0

Marek Sotak
Marek Sotak

Reputation: 136

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.

Upvotes: 0

user1796666
user1796666

Reputation:

You can't access the parent from your iframe if it's in another domain.

Upvotes: 1

Related Questions