2017-03-04 81 views
1

我使用Javascript单击按钮并在弹出窗口中显示它,动态创建iframe。
在Iframe中,我正在加载另一个网站(不同的域),它由从第一步到最后一步的用户的表单序列组成。
当用户处于最后一步时,他将在Iframe内获得一个关闭按钮。
我想关闭(隐藏)单击关闭按钮时包含Iframe的弹出窗口。
可能吗?请帮忙。关闭包含Iframe的Popup,单击iframe上的按钮

回答

2

后浏览网页寻找解决办法,我碰到这个soultion来小时。
这里的问题是,同源策略会阻止脚本访问其他来源网站内容。
其实原点由以下几部分组成。

origin:<protocol(http/https)>://<hostname>:<port number>/path/to/page.html 

起源被认为是不同的,如果协议主机名端口号没有same.In这种情况下,你不能从其他网站访问一个网站的内容,由于相同 - 原始安全政策。

为了克服它,你必须使用通过window.postMessage()亲子沟通
供参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Window.postMessage()方法安全地启用了跨源通信。
假设你的父母的网站是example-parent.com并在您的iFrame加载网站example-iframe.com,让两者都使用HTTP协议。 以下是我如何解决问题。
在父网站中添加要接收消息的事件侦听器,如下所示。

window.addEventListener('message',receiveMessage,false); 

function receiveMessage(event){ 
    var origin = event.origin || event.originalEvent.origin; 
    if(origin.indexOf('http://example-iframe.com')>=0) // check if message received from intended sender 
    { 
     if(event.data=="intended message format") // check if data received is in correct format 
     { 
      // call functionality that closes popup containing iframe 
     }else{ // data received is malacious 
      return; 
     } 

    }else{ // message is not received from intended sender 
     return; 
    } 
} 

从Iframe发送消息到父网站如下。
帖子消息语法:otherWindow.postMessage(message, targetOrigin, [transfer]);

function sendMessage(){ 
    parent.postMessage('intended message format','http://example-parent.com'); 
} 

使用的postMessage()正确,否则可能会导致跨站点脚本攻击。

+1

另外,如果你的事件监听器正在引起一些网络调用,建议检查收到的消息的速率,这是为了防止DOS攻击。 – nak

0

因为我正确理解你想调用一个关闭iframe的子项(关闭iframe中的按钮)的函数。您可以通过调用做到这一点父

parent.myfunction() //call myfunction from parent 

而且在父母的代码,你必须执行关闭逻辑

myfunction() { 
    iframe.hide() //or whatever 
    } 
+0

只有在父网站的起源和在Iframe中加载的网站的起源相同时,它才能起作用。 – Learnquick

+0

是的,在两个网站中都放了document.domain ='same.domain' –