[英]Allowing a parent window to call a function on its child iframe of a different domain
I have an iframe in which src is different domain, and I am trying to call a method in iframe from parent window. 我有一个src是不同域的iframe,并且我试图从父窗口调用iframe中的方法。 Then it is giving below: 然后它给出如下:
Uncaught SecurityError: Blocked a frame with origin " http://localhost:8080 " from accessing a frame with origin " http://stage.xyz.com ". 未捕获的SecurityError:阻止了源为“ http:// localhost:8080 ”的框架访问源为“ http://stage.xyz.com ”的框架。 Protocols, domains, and ports must match. 协议,域和端口必须匹配。
On main window I have this: 在主窗口上,我有这个:
launchUPwidget(widgetParams);
function launchUPwidget(widgetParams){
document.getElementById('iframe').contentWindow.invokeUPWidget(widgetParams);
}
On iframe: 在iframe上:
window.invokeUPWidget = invokeWidget;
So how can I call a function in child iframe form parent window where iframe src is different domain? 那么,如何在子iframe父窗口(其中iframe src是不同域)中调用函数?
here protocals are same but the domains are different. 这里的协议是相同的,但领域是不同的。
You can't access an <iframe>
with Javascript, it would be a huge security flaw if you could do it. 您无法使用Javascript访问<iframe>
,如果可以的话,这将是一个巨大的安全漏洞。
For the same-origin policy every browser blocks any script trying to access a frame with a different origin. 对于同源策略,每个浏览器都会阻止任何试图访问具有不同来源的框架的脚本。
Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, if you own both the pages, you can work around this problem using window.postMessage and its relative message event to send messages between the two pages, like this: 即使同源策略阻止脚本访问来源不同的站点的内容,但是如果您同时拥有两个页面,则可以使用window.postMessage及其相对消息事件在两个页面之间发送消息,从而解决此问题。这个:
In your main page: 在您的主页中:
var frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, '*');
In your (contained in the main page): 在您的(包含在主页中):
window.addEventListener('message', function(event) {
// IMPORTANT: Check the origin of the data!
if (event.origin.indexOf('http://yoursite.com')) {
// The data has been sent from your site
// The data sent with postMessage is stored in event.data
console.log(event.data);
} else {
// The data hasn't been sent from your site!
// Be careful! Do not use it.
return;
}
});
There is a similar question . 还有一个类似的问题 。 You can read about it more there. 您可以在此处了解更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.