IFrame Popup “Window”, Show & Hide, Cross Domain

2019-08-01 07:51发布

I have a web page, designed as a popup window that must be hosted by many external web sites. When the user clicks on a button in the hosting web page, the button should cause my iFrame to display. The user then interacts with my iFrame'd page to complete a specific task and eventually clicks the "close" button within my page and the frame becomes hidden again. However, because the two documents reside in different domains (and must do so), I am running up against browser security restrictions.

My hosting page can't manipulate CSS within the hosted iFrame to change it to display:block, though it can so manipulate the frame itself. And the hosted iFrame can't "reach up" to the iFrame element to manipulate its CSS to change the iFrame display to/from block/hide.

I can't see a way forward to having a button in the hosting document show the iFrame and/or its contents while at the same time having a button in the hosted document be able to manipulate the same element to hide the iFrame and/or its contents.

Open to any creative solutions as long as it doesn't require a third-party JS library, since we have little to no control over the hosting sites and want to impose as little as possible on them - ideally, we supply a tiny snippet of HTML which they embed in their page to use our interactive service.

Also, and as something of an aside, when I show the iFrame itself from the hosting document, the entire display is replaced by the iFrame instead of the iFrame overlaying it with the hosting document still visible behind it.

2条回答
劫难
2楼-- · 2019-08-01 08:08

Very inefficient, but it works.

On the iframe page, add <a href="#" onclick="window.top.location.hash='close'">Close</a>

And on the page that has the iframe on it add

Javascript:

setInterval(function(){check()},1);
function check() {
if(window.location.hash=='#close') {
document.getElementById('frame').style.display='none';
}
}

HTML:

<iframe id="frame" src=""></iframe>
查看更多
不美不萌又怎样
3楼-- · 2019-08-01 08:22

The only way I could find to do this is using Cross Domain Messaging.

With the frame initially styled display:none, and the hosting page onclick handler setting display:block, add this JavaScript to the hosting page:

<script>
  window.onmessage=function(msg) {
      var fra=document.getElementById("~~frame-id-here~~");
      if(msg.data && msg.data.name=="Close" && msg.source==fra.contentWindow) {
          fra.style.display="none";
          }
      };
</script>

and in the hosted iFrame, just do this when you want to close (hide) the frame:

parent.postMessage({name:"Close"}, "*");

Note: If you know the URL for the parent ahead of time use it instead of "*" in the second argument.

Also, older versions of IE (8 and earlier, IIRC) cannot handle an object parameter, so for those you need to use:

parent.postMessage("Close", "*");

and handle it appropriately in the parent as a simple string "command".

查看更多
登录 后发表回答