Javascript window.opener in iframe

2019-05-28 22:43发布

问题:

I am trying to access the opener of a popup using the window.opener reference in the popup's script file.

Consider the following script included in the popup.html:

http ://localhost/test/popup.html

<script>
    alert(window.opener.test_dom);
</script>

This works when no iframe is involved, we will see the alert message from popup.html:

http ://localhost/test/base.html

 <html>
  ...
  <script> 
      var test_dom = 'test_dom';
      var popup = window.open("http://localhost/test/popup.html",...
  </script>
 </html>

The problem exists when there are 3 files.. a container page with an iframe in it that launches a popup from within that iframe. This does not show the alert message when popup appears:

C:\TestContainer\container.html

 <html>
  ...
  <iframe src="http://localhost/test/base.html">
      <script> 
          var test_dom = 'test_dom';
          var popup = window.open("http://localhost/test/popup.html",...
      </script>

  <iframe>
 </html>

Perhaps this is a security restriction? AFAIK base.html and popup.html are in the same domain, so I see no reason why this should be. Are there other ways to access the opener via other DOM attributes in the popup.html script? I've been stuck on this for a day now.

Other than the reference to opener, everything else seems to work as expected in all scripts.

Using IE 11.

Any assistance is appreciated!

回答1:

An iframe does not have a window.opener. It has a window.parent (the window in which the iframe is embedded). If the parent is indeed the top level window, then perhaps that window has a window.opener if its the actual popup window.

You haven't shown your specific HTML situation, but perhaps what you want from the iframe is this:

window.parent.opener


回答2:

I came up with a workaround to this problem. In my situation, the popup was very simple, so what I did was embed its html in a hidden div in the base page. Then, when the popup was needed, I simply made the window show the contents of the hidden html.

Unfortunately, the event processing for the buttons found in the popup do not automatically get set when this is done, so I had to manually set them using addEventListener once the window was shown (ie, putting 'onclick' events in the html tags will not work).

   var popup = window.open("", "_blank", "..", false);
   var popup_html = window.document.getElementById('hidden_popup_contents').innerHTML;
   popup.document.writeln(popup_html);
   popup.document.getElementById('popup_button').addEventListener('click', SomeFunction);