关于在iframe中,跨域调用parent页面的方法的问题

js报错信息:Uncaught SecurityError: Blocked a frame with origin "http://127.0.0.1:8080" from accessing a frame with origin "http://localhost:8888". Protocols, domains, and ports must match.

不支持跨域调用javascipt方法,例如:window.parent.func();这种调用方式不被支持,跨域的时候会报上面的错误。

我的解决方法是用html5的方法:postMessage。

在iframe中触发postMessage方法,向父窗体发送message。父窗体监听消息,根据message中传递的不同的标志,做不同的处理。

实例代码:

//iframe中跨域通信
function postMessage(data){
	var post = {type:type,data:data};
	window.parent.postMessage(post,'*');
}
//父窗体中监听消息
window.addEventListener('message',function(e){
    var color=e.data;
    switch(parseInt(color.type)){
   		case 1:
			break;
		case 2:
			break;
		default:break;
	}
}
 
  

详细可以参考大神详细解读postMessage方法:

html5 postMessage解决跨域、跨窗口消息传递

你可能感兴趣的:(#,前端技术)