我有一个来自domain1.com的网页,那里有一个domain2.com的iframe,然后在domain3.com的domain2.com内有另一个iframe
我想在domain2.com中拦截来自domain3.com的消息,如果domain2.com不在domain1.com内,则消息正确接收,但是如果我在domain1.com内有domain2.com,则消息来自domain1.com而非domain2.com接收domain3.com。有什么办法可以在domain2.com中捕获这些消息?
结构是这样的
domain1.com具有内部iframe src =“ domain2.com” domain2.com具有内置的iframe src =“ domain3.com”
当我直接访问domain2.com时,它捕获了domain3.com消息,当我访问domain1.com时,domain1.com而不是domain2.com接收到从domain3.com发送的消息
答案 0 :(得分:5)
我试图重新创建您的iframe地狱。希望这是您要寻找的。这应该涵盖您上面列出的方案。如果我误解了什么,请告诉我。
我还创建了一个Plunker
index.html (域1)
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
domain 1
<form id="form">
<input type="text" placeholder="Enter message" name="message">
<input type="submit" value="Click to send">
</form>
<iframe src="domain2.html" id="iframe" style="display:block;height:120px"></iframe>
<script>
window.addEventListener('message', function(event){
const [message, domain] = event.data.split('|');
alert(`domain1: Received ${message} from ${domain}`);
});
form.onsubmit = function() {
iframe.contentWindow.postMessage(`${this.message.value}|domain1`, '*');
return false;
};
</script>
</body>
</html>
domain2.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
domain 2
<form id="form">
<input type="text" placeholder="Enter message" name="message">
<input type="submit" value="Click to send">
</form>
<iframe src="domain3.html" id="iframe" style="display:block;height:60px"></iframe>
<script>
window.addEventListener('message', function(event){
const [message, domain] = event.data.split('|');
alert(`domain2: Received ${message} from ${domain}`);
});
form.onsubmit = function() {
iframe.contentWindow.postMessage(`${this.message.value}|domain2`, '*');
return false;
};
</script>
</body>
</html>
domain3.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
domain 3
<form id="form">
<input type="text" placeholder="Enter message" name="message">
<input type="submit" value="Click to send">
</form>
<script>
window.addEventListener('message', function(event){
const [message, domain] = event.data.split('|');
alert(`domain3: Received ${message} from ${domain}`);
});
form.onsubmit = function() {
window.parent.postMessage(`${this.message.value}|domain3`, '*');
return false;
};
</script>
</body>
</html>