我在一个项目中工作,我想在一个iframe中填充网页,但由于CORS,我无法从我的应用程序与iframe内的内容进行交互,但将在我的应用程序内显示他们的网页的人可以在他们的网页上安装代码或其他东西,我尝试了postMessage,但似乎它很容易被利用,如果有人想的话。
我想知道我是否可以开发一种API,可以放在用户的网页上,只有当有人从我的应用程序访问它时才会被激活,并允许用户在iframe中使用自定义事件与网页进行交互?
我们使用react js作为前端。
这样的事情是可能的吗?如果是,是如何实现的?谷歌分析跟踪代码是如何工作的我相信它也使用了postMessage。
非常感谢您的帮助。如果你能帮我的话我很乐意赞助一杯咖啡。
发布于 2020-09-19 03:16:41
我有一个非常类似的问题,网页是我的,而iframe内容有一个我的脚本标签。下面是两种方式的通信方式: iframe到parent,以及parent到iframe。
此代码充当一种侦听器,用于侦听来自其他窗口的消息。如果你想要双向交流,你需要在两个页面上,你的客户和你自己的页面(嵌入页面和嵌入页面):
window.onmessage = function(e) {
// this get's triggered when other window sends a message
if (e.data == "<some_identifier>") {
// with e.data you can send an identifier
// and then you put the code that should be executed in here (on your page)
} else if (e.data == "<some_other_identifier>") {
// other action to do
}
};
您可以使用如下所示的postMessage
函数从嵌入式iframe网站发送这些消息,以便发布到父窗口(嵌入窗口)
window.top.postMessage("<some_identifier>", "*");
反过来,您可以像这样嵌入页面,名称必须是唯一的
<iframe src="<your-embedded-url>" name="<some-id>"/>
然后你可以发一篇这样的帖子:
let target = window.frames.<some-id>;
target.postMessage("<some_identifier>", "*");
postMessage
中的星号将决定消息是针对您的每个窗口,还是仅针对特定的一个窗口(例如,您可以发送仅针对您的网站的消息,其他嵌入站点则无法接收该事件。More infos on restricting the target here。
如果您有任何问题,请提出来:)
https://stackoverflow.com/questions/63933866
复制相似问题