Пожалуйста, у меня есть небольшая форма, которую я открываю в окне popop, как показано ниже.postMessage from iframe открыт в новом окне
<html>
<head>
</head>
<body>
<div id="popUpDiv" style="display:none;"></div>
<script type="text/javascript">
var popUpWindow;
function popup(n) {
popUpWindow = window.open("",n, "height=500,width=500");
}
function foo(obj){
test1 = "http://localhost:3001";
popUpWindow.document.write('<iframe height="450" id="receiver" allowTransparency="true" frameborder="0" scrolling="yes" style="width:100%;" src="'+test1+'" type= "text/javascript"></iframe>');
}
</script>
<a href="#" onclick="popup('popUpDiv');foo(this);">OnSale</a>
</body>
</html>
выше является родительской формой и работает на сервере localhost: 3000. Я открыл новое окно с iframe. Я намереваюсь postMessage из всплывающего окна или дочернего окна и получать его в родительском окне. Затем я изменил свой код, добавив нагрузку ниже.
window.onload = function() {.
var messageEle = document.getElementById('message');
console.log('its receiving message');
function receiveMessage(e) {
alert('received');
console.log('the origin is ', e.origin);
if (e.origin !== "http://localhost:3001"){
return;
}
messageEle.innerHTML = "Message Received: " + e.data;
}
window.addEventListener('message', receiveMessage);
}
моя полная родительская страница теперь выглядит ниже.
<html>
<head>
</head>
<body>
<div id="popUpDiv" style="display:none;"></div>
<script type="text/javascript">
var popUpWindow;
function popup(n) {
popUpWindow = window.open("",n, "height=500,width=500");
}
function foo(obj){
test1 = "http://localhost:3001";
popUpWindow.document.write('<iframe height="450" id="receiver" allowTransparency="true" frameborder="0" scrolling="yes" style="width:100%;" src="'+test1+'" type= "text/javascript"></iframe>');
}
window.onload = function() {
var messageEle = document.getElementById('message');
console.log('its receiving message');
function receiveMessage(e) {
alert('received');
console.log('the origin is ', e.origin);
if (e.origin !== "http://localhost:3001"){
return;
}
messageEle.innerHTML = "Message Received: " + e.data;
}
window.addEventListener('message', receiveMessage);
}
</script>
<a href="#" onclick="popup('popUpDiv');foo(this);">OnSale</a>
<div id="message"></div>
</body>
</html>
Когда я нажимаю Onsale ссылку на родителя, он открыл мой ребенок с сервера 3001. Однако, работающие на детской консоли
parent.postMessage('Hello', 'http://localhost:3000');
не срабатывает событие receiveMessage из родитель. Я подтвердил, что мое мероприятие прилагается. Я пробовал все возможное, но ничего не изменилось. Пожалуйста, что я делаю неправильно? любая помощь будет оценена
Спасибо, это работает для меня в аналогичном случае. При запуске в новом окне ** postMessage ** необходимо отправить ** открыватель ** вместо ** parent **. В моем случае мне нужно заставить его работать для обоих случаев, поэтому я проверяю наличие открывателя: 'openener? opener.postMessage ('Hello', 'https: //target.url'): parent.postMessage ('Hello', 'https: //target.url') ' – Rafa