-
-
Save AlliotTech/5f7826601242c8fd3b7ff1530f28db1f to your computer and use it in GitHub Desktop.
跨域通信机制 - postMessage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>a-domain</title> | |
</head> | |
<body> | |
<h1>跨域通信机制 - postMessage</h1> | |
<h2>a-domian.html</h2> | |
<iframe class="js-iframe" src="http://localhost:3000/other-domain.html"></iframe> | |
<script> | |
function sendMessage2Child() { | |
var iframe = document.querySelector('.js-iframe'); | |
var iframeWindow = iframe.contentWindow; | |
// 注意: 必须在 iframe onload 之后父级才能给子级发消息 | |
iframe.onload = function() { | |
// targetOrigin: iframe(消息接收者)所在的域名, 即目标的域名 | |
// 可以这样简单的记忆: 调用 window.postMessage 时, 这个 window 所在的域名 | |
// 例如 | |
// * 使用 iframe.contentWindow 指的就是 iframe 所在的域名 | |
// * 在 iframe 中使用 parent.postMessage 即 parent 所在的域名 | |
// | |
// 因此你没有办法伪造域名, 因此不到万不得已, 不要使用 "*" | |
var targetOrigin = 'http://localhost:3000'; | |
// 要发送消息给谁, 就使用谁的 window 对象 | |
iframeWindow.postMessage('在父级发送消息给子级(父级给子级的数据)', targetOrigin); | |
}; | |
} | |
function receiveChildMessage() { | |
// 监听子级给父级发送过来的消息 | |
window.addEventListener('message', function(event) { | |
// event.origin: 消息来源(发消息的人) | |
// 正式环境下一般都需要做消息来源的过滤以免出现安全问题 | |
console.log('消息传递', event.origin, '->', window.location.href, event.data); | |
}, false); | |
} | |
sendMessage2Child(); | |
receiveChildMessage(); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>other-domain.html</title> | |
</head> | |
<body> | |
<h1>other-domain.html</h1> | |
<script> | |
function receiveParentMessage() { | |
// 监听父级给子级发送过来的消息 | |
window.addEventListener('message', function(event) { | |
console.log('消息传递', event.origin, '->', window.location.href, event.data); | |
// 可以在这里通过 event.source 给父级发送消息 | |
// event.source.postMessage('子级->父级', 'http://localhost:8000'); | |
}, false); | |
} | |
function sendMessage2Parent() { | |
// 调用 parent.postMessage, targetOrigin 为 parent 所在的域名 | |
var targetOrigin = 'http://localhost:8000'; | |
// 子级发送消息给父级 | |
parent.postMessage('在子级发送消息给父级(子级给父级的数据)', targetOrigin); | |
} | |
receiveParentMessage(); | |
sendMessage2Parent(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment