【发布时间】:2011-11-20 17:02:42
【问题描述】:
我有一个可嵌入的 iframe,将在 3rd 方网站上使用。它有几个表格要填写,最后必须通知父页面已完成。
换句话说,点击按钮时,iframe 需要向其父级传递消息。
在经历了“不,跨域策略是个混蛋”的海洋之后,我找到了window.postMessage,它是 HTML5 草案规范的一部分。
基本上,您在页面中放置以下 JavaScript 以从 iframe 捕获消息:
window.addEventListener('message', goToThing, false);
function goToThing(event) {
//check the origin, to make sure it comes from a trusted source.
if(event.origin !== 'http://localhost')
return;
//the event.data should be the id, a number.
//if it is, got to the page, using the id.
if(!isNaN(event.data))
window.location.href = 'http://localhost/somepage/' + event.data;
}
然后在 iframe 中,有一些 JavaScript 向父级发送消息:
$('form').submit(function(){
parent.postMessage(someId, '*');
});
太棒了,对吧?唯一的问题是它似乎不适用于任何版本的 IE。所以,我的问题是:鉴于我需要将消息 从 一个 iframe 传递给它的父级(我都控制这两个),有没有一种我可以使用的方法可以跨任何 (>IE6) 浏览器?
【问题讨论】:
标签: javascript html iframe embed