如何关闭外部 iframe src

时间:2021-04-11 09:40:48

标签: java php html iframe

如何使用带有 iframe 的点击事件关闭 iframe src? 假设我有这个父 html

<body>
<script>
document.write("<iframe src='default.html' id="myFrame" width='100%'></iframe>");


function closeIframe(){
   $('#myFrame').remove();
}
</script>
</body>

我有一个带有代码的 iframe default.html:

<input type="checkbox" name="iframe" value="" onchange="parent.closeIframe()">

我希望能够在单击复选框时关闭 iframe。上面的代码对我不起作用。我需要帮助。

1 个答案:

答案 0 :(得分:1)

这需要外部站点和内部站点之间的合作+两个站点上的一段Javascript。

在外部,听众需要对发布的消息做出反应:

window.addEventListener('message', function(event) {

  if (event.origin !== 'https://inner.example.com') return;
  if (typeof event.data != 'string') return;
  
  // do your stuff...
  if (message == 'hello_world') {
    // react on the message
  }
});

网址“https://inner.example.com”指的是 iframe 内的网站。 从那里,像这样将命令发布到外部站点。对消息来源的检查是为了拒绝来自其他(未知)站点的消息。

parent.postMessage('hello_world', 'https://outer.example.com');

网址“https://outer.example.com”是指包含 iframe 的网站。

消息可以是任意的,但是在这个例子中只接受一个字符串。字符串的内容可以是任何...

您应该注意,如果外部和内部来自不同的域(安全策略),浏览器可能会阻止此消息发送。