是的,您可以这样做。
您可以实现window.postMessage来跨域通信,包括在iframes和/或窗口之间进行通信。
但是需要以异步方式执行。
如果您需要同步执行,您需要在这些异步方法周围实现包装器。
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<!--
<link rel="shortcut icon" href="/favicon.ico">
<link rel="start" href="http://benalman.com/" title="Home">
<link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">
<script type="text/javascript" src="/js/mt.js"></script>
-->
<script type="text/javascript">
function SendMessage()
{
var win = document.getElementById("ifrmChild").contentWindow;
if (win == null || !window['postMessage'])
alert("oh crap");
else
win.postMessage("hello", "*");
}
function ReceiveMessage(evt) {
var message;
if (false) {
message = 'You ("' + evt.origin + '") are not worthy';
}
else {
message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
}
var ta = document.getElementById("taRecvMessage");
if (ta == null)
alert(message);
else
document.getElementById("taRecvMessage").innerHTML = message;
}
if (!window['postMessage'])
alert("oh crap");
else {
if (window.addEventListener) {
window.addEventListener("message", ReceiveMessage, false);
}
else {
window.attachEvent("onmessage", ReceiveMessage);
}
}
</script>
</head>
<body>
<iframe id="ifrmChild" src="child.htm" frameborder="0" width="500" height="200" ></iframe>
<br />
<input type="button" value="Test" onclick="SendMessage();" />
</body>
</html>
Child.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<!--
<link rel="shortcut icon" href="/favicon.ico">
<link rel="start" href="http://benalman.com/" title="Home">
<link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">
<script type="text/javascript" src="/js/mt.js"></script>
-->
<script type="text/javascript">
function ReceiveMessage(evt) {
var message;
if(false)
{
message = 'You ("' + evt.origin + '") are not worthy';
}
else
{
message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
}
var ta = document.getElementById("taRecvMessage");
if(ta == null)
alert(message);
else
document.getElementById("taRecvMessage").innerHTML = message;
evt.source.postMessage("thanks, got it", "*");
}
if (!window['postMessage'])
alert("oh crap");
else {
if (window.addEventListener) {
window.addEventListener("message", ReceiveMessage, false);
}
else {
window.attachEvent("onmessage", ReceiveMessage);
}
}
</script>
</head>
<body style="background-color: gray;">
<h1>Test</h1>
<textarea id="taRecvMessage" rows="20" cols="20" ></textarea>
</body>
</html>
在这里,你需要修改子页面,使其向父页面发送postmessages。
例如,在child.htm中,你需要这样做:
window.parent.postMessage("alert(document.location.href); document.location.href = 'http://www.google.com/ncr'", "*");
在父页面中,在receiveMessage函数中使用以下代码:
eval(evt.data);
。需要注意的是,使用eval存在安全风险,因此最好使用枚举方式传递信息,并调用相应的函数在父页面上执行。