javascript - 在我的页面和 iframe 之间进行通信并相互发送数据
问题描述
我正在尝试在我的页面和另一个 iframe 之间进行通信,这是另一个页面,我有,
在我的 iframe 页面上,我在头部插入了这个脚本
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;
}
});
}
在我想与 iframe 通信的主页上,我有这段代码,
<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>
第一个警报有效,它弹出,但没有别的。有人可以帮我解决这个问题。非常感谢。
解决方案
推荐阅读
- c# - 将一个文档插入另一个 Microsoft.Office.Interop.Word
- python-3.x - 将 docx 文件与 python docx 组合的问题
- mysql - 在mysql中嵌套IF()选择?
- python - UltiSnips 在 vim 中不起作用:E887:抱歉,此命令已禁用,无法加载 Python 的站点模块
- c# - 结合2个select语句和join sql
- java - 更新列表中的现有对象
- c# - 将正则表达式字符串传递给程序集
- google-chrome - Chrome 扩展程序未显示在商店中
- r - R:hunspell 总是返回 false
- elasticsearch - 在现有索引的现有字段中添加带有分析器的多字段