mahesh
mahesh

Reputation: 4763

How to get parent domain name in iframe with cross domain?

I want to get the parent domain or url or hostname inside iframe javascript.

I have used document.referrer for that, but it only works the first time. By this I mean that my iframe contains the form so when the user submits the form the iframe loads again and the referrer will become the my iframe's domain.

Now each time my iframe loads I want the parent domain name only as I am creating the links using that.

Example:

$(".setUrl").each(function(){
                var referrer = document.referrer;
                this.href=referrer+"/abc.html";
  });

But this only works the first time because of the reason I mentioned above. So can somebody help me overcome this?

Ask me in case if more clarity required.

Upvotes: 9

Views: 8987

Answers (2)

Siddharth Gupta
Siddharth Gupta

Reputation: 897

The moment you have the parent domain URL inside the iFrame (from the document.referrer), you can store that URL in the localStorage, and then after the form is submitted, retrieve it back from the localStorage itself.

Something like:

var referringURL = document.referrer;
//store the url in localStorage 
localStorage['referrer'] = referringURL; 

Now after the form is submitted:

var originalReferrer = localStorage['referrer'];
//you have the original referrer back

Upvotes: 4

Manan Shah
Manan Shah

Reputation: 1098

You can do one thing for this:

  1. Save your parent domain / url / hostname in some hidden variable in your form.And submit that form.
  2. Do not set/save/use documentReferrer value from current url. When you need, use the hidden variable.

You can use any logic... e.g:

var refval=$("#documentReferrer").val();
if(refval=="")
{
     $("#documentReferrer").val(referrer); //So, for the future, this will not execute...
}

Upvotes: 1

Related Questions