The problem of communication between parent page and iframe page is solved by pseudo protocol

  • 2020-05-26 07:50:27
  • OfStack

We often have parent page and iframe page operations, for example

< iframe id = "iframe" > < /iframe >

What's in iframe is written by js. As follows

var iframe = document.getElementById("iframe"),
  doc = iframe.contentWindow.document;;

The above code is correct in most cases. But in some cases, the parent page explicitly says document. domain = "xxx";

Unauthorized errors occur in the ie series (IE10 has not been tried). At firefox, chrome is fine.

Why is that? ? This is one bug of ie, that is, when the parent page does not explicitly set document.domain, iframe will default to document.domain and parent page 1, that is, both, the parent page is an example of an article header that can be communicated, but when the parent page explicitly sets document.domain ="", the page inside iframe must also explicitly set document.domain ="xxx", otherwise it is

If you don't have permission to get iframe.contentWindow.document, you won't be able to write content dynamically, but you can have iframe point to a particular page, which explicitly sets document.domain ="xxx", and then go to the beginning of the article

The way to write, but the problem is that my parent page has a lot of such iframe, the number is unknown (are advertising space), so also can not go through the specific page.

So the problem is, in this case, there's nothing we can do about it

1. The parent page is set and must explicitly set document.domain

2. The content of iframe page needs to be dynamically generated by js.

3. No opportunity to set src for iframe.

However, when the above three conditions are met, we can solve this kind of problem through the pseudo-protocol.

iframe.src="javascript:void((function(){var d=document;;d.domain='xxx;d.write('---something');d.close()})())";

This way you can explicitly set iframe's document.domain to parent page 1.

This does fulfill the need to dynamically write iframe content, but the page will pop up separately, like ();
Why is that? This is also the bug of the ie series, which the parent page has < base target="_blank" > < /base > , the content written through the pseudo-protocol of iframe will pop up a new page like window.open1.
But for the parent page < base > It must also be _self, so you can only set target of base to _self before calling iframe.src, and then set target of base to _blank after writing the content

That solves the problem.

Although fake protocols can solve this problem, there are some risks. Don't use this method unless you have to.

Related articles: