I'm trying to communitacting between my page and another iframe that is another page, which I have,
On my iframe page, I inserted this script on the head
if(typeof window !== 'undefined'){
window.addEventListener('message', event => {
if (event.origin.startsWith('https://testpage.com/')) {
document.querySelector('.home-title').classList.add('test');
event.source.postMessage('iframe', event.origin);
} else {
return;
}
});
}
and on my main page where I want to communicate with my iframe, I have this code,
<script>
window.onload = function () {
setTimeout(() => {
const iframe = document.querySelector('iframe');
const iframeWindow = iframe.contentWindow;
iframeWindow.postMessage("Hello there" , 'https://testIfame.com/');
alert('here alert pops-u');
}, 3000)
window.addEventListener('message', function(event) {
if (event.origin == 'https://testpage.com/'){
alert('asd');
}
}, false);
}
</script>
The first alert, works, it pops up, but nothing else. Can somebody help me to resolve this. Thanks a lot.