Javascript 单击Iframe中的按钮,关闭包含Iframe的弹出窗口
我使用Javascript在点击按钮时动态创建一个Iframe,并在弹出窗口中显示它Javascript 单击Iframe中的按钮,关闭包含Iframe的弹出窗口,javascript,jquery,html,iframe,Javascript,Jquery,Html,Iframe,我使用Javascript在点击按钮时动态创建一个Iframe,并在弹出窗口中显示它在Iframe中,我正在加载另一个网站(不同的域),它由一系列表单组成,将用户从第一步带到最后一步。当用户处于最后一步时,Iframe中会给他一个关闭按钮我想在单击关闭按钮时关闭(隐藏)包含Iframe的弹出窗口。 有可能吗?请帮助。正如我正确理解的那样,您希望从child(iframe中的close按钮)调用一个函数来关闭iframe。你可以打电话给家长 parent.myfunction() //call m
在Iframe中,我正在加载另一个网站(不同的域),它由一系列表单组成,将用户从第一步带到最后一步。
当用户处于最后一步时,Iframe中会给他一个关闭按钮
我想在单击关闭按钮时关闭(隐藏)包含Iframe的弹出窗口。
有可能吗?请帮助。正如我正确理解的那样,您希望从child(iframe中的close按钮)调用一个函数来关闭iframe。你可以打电话给家长
parent.myfunction() //call myfunction from parent
在父代码中,您必须实现关闭逻辑
myfunction() {
iframe.hide() //or whatever
}
在网上冲浪数小时寻找解决方案后,我遇到了这个问题。
这里的问题是,同源策略阻止脚本访问其他来源的站点内容。
实际上,同源策略由以下部分组成
origin:<protocol(http/https)>://<hostname>:<port number>/path/to/page.html
从Iframe向父网站发布消息,如下所示。Post消息语法:
otherWindow.postMessage(消息,targetOrigin,[transfer])代码>
正确使用postMessage(),否则可能会导致跨站点脚本攻击。只有当父网站的来源与Iframe中加载的来源相同时,它才会起作用。是的,将document.domain='Same.domain'放在两个网站中也一样,如果您的事件侦听器导致一些网络呼叫,建议您检查接收消息的速率,这是为了防止DOS攻击。非常感谢您的回答,我花了一整天时间,效果非常好。
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;
}
}
function sendMessage(){
parent.postMessage('intended message format','http://example-parent.com');
}