当使用iframe时,如何从iframe中的iframe获取属性值?
这是我的代码:
<iframe src="slideriframe.html" name="iframe_a" customAttr="example" style="border:none"></iframe>以下是我目前的情况:
alert(window.frameElement.getAttribute('customAttr'));以下是错误:
Uncaught :无法从“窗口”读取' frame‘属性:阻止原始“空”的框架访问原名为"null“的帧。协议、域和端口必须匹配。
谢谢
发布于 2015-06-23 20:01:07
您需要使用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);这些示例使用原产地属性限制消息发送到何处,并检查消息来自何处。可以指定*来允许发送到任何域,而且在某些情况下,您可能希望接受来自任何域的消息。但是,如果您这样做,您需要考虑到安全问题,并对传入的消息执行您自己的检查,以确保它包含您期望的内容。在这种情况下,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;
}https://stackoverflow.com/questions/30971447
复制相似问题