您需要使用postMessage API提供了一个在iFrame和它的父级之间进行通信的简单方法。您将向父母发送消息,然后查找该值并将其他消息发回给iFrame。
要给父页面发送消息,请按以下方式调用它。
parent.postMessage('Hello parent','http://origin-domain.com');
在另一个方向上,我们可以使用以下代码将消息发送到iFrame。
var iframe = document.querySelector('iframe');
iframe.contentWindow.postMessage('Hello my child', 'http://remote-domain.com:8080');
若要接收消息,请为消息事件创建事件查找器。
function receiveMessage(event)
{
if (event.origin !== "http://remote-domain.com:8080")
return;
console.log(event.data);
}
if ('addEventListener' in window){
window.addEventListener('message', receiveMessage, false);
} else if ('attachEvent' in window){ //IE
window.attachEvent('onmessage', receiveMessage);
这些示例使用origin属性限制消息发送到的位置,并检查它来自哪里。可以指定*
以允许发送到任何域,并且在某些情况下您可能想要接受来自任何域的消息。但是,如果您这样做,则需要考虑安全隐患并对收到的消息执行自己的检查,以确保它包含您的期望。在这种情况下,iframe可以将它的高度发布为'*',因为我们可能有多个父域。但是,检查来自iFrame的传入消息是个好主意。
function isMessageFromIFrame(event,iframe){
var
origin = event.origin,
src = iframe.src;
if ((''+origin !== 'null') && (origin !== src.substr(0,origin.length))) {
throw new Error(
'Unexpect message received from: ' + origin +
' for ' + iframe.id + '. Message was: ' + event.data
);
}
return true;
}
你不能,如果iframe来自另一个域。对于其他解决方案,阅读在SO上提供的其他解答,例如http://stackoverflow.com/questions/217776/how-to-apply-css-to-iframe – cari
你看到这个错误的原因是因为[同源策略](https://en.wikipedia.org/维基/同-origin_policy)。用非常简单的话来说,这意味着你不能访问不属于你的代码。有几种方法可以放宽此政策,但您可以在我已链接的Wiki页面上阅读更多内容。 – icecub