gpt4 book ai didi

javascript - 如何将事件从子窗口发送到其父窗口

转载 作者:可可西里 更新时间:2023-11-01 02:10:04 27 4
gpt4 key购买 nike

我的主要目标是:

转到我的应用程序,在新选项卡中打开一个链接,在新选项卡中创建一些内容,然后将事件发送到父主选项卡以进行刷新。

我学到了 2 种不能完全满足我需要的技术:

  1. postMessage - 据我所知只在 iframe 上有效,在选项卡上无效
  2. window.opener - 仅适用于 window.open(url),它只打开新窗口而不是新标签。

如何使用选项卡将事件从子项传递到父项?我很乐意为 parent 和 child 中的 javascript 代码提供一个具体示例。它应该适用于跨域(例如:www.mydomain.com 和 bills.mydomain.com)。

是否有我缺少的 jQuery 解决方案?

最佳答案

以下适用于我的 chrome、firefox、ie(没有测试更多浏览器)

假设有 3 个文档

  1. (www.mydomain.com/parent.html)包含带有链接的“主”文档的页面
  2. (bills.mydomain.com/child.html)链接打开的页面
  3. (www.mydomain.com/dispatcher.html)稍后解释

首先将所有3个文档的domain-property设置为mydomain.com

<script>
document.domain="mydomain.com";
</script>

在 parent.html 中创建一个隐藏的 iframe,其名称属性为例如“隐藏框架”。还要创建一些稍后可能会收到响应的函数。

parent.html 现在应该是这样的:

<script>
document.domain="mydomain.com";
function fx(msg)//receives the response
{
alert(msg)
}
</script>
<iframe name="hiddenframe" style="display:none"></iframe>
<a href="http://bills.mydomain.com/child.html" target="_blank">click</a>

在 child.html 中,您现在可以将文档加载到 parent.html 中隐藏的 iframe 中

<script>
document.domain="mydomain.com";
window.open('http://www.mydomain.com/dispatcher.html','hiddenframe');
</script>

(不要对这里使用window.open()感到困惑,那里不会打开新窗口,页面会加载到parent.html中的iframe中)


在 dispatcher.html 中,您现在可以调用 parent.html 中的函数

<script>
document.domain="mydomain.com";
parent.fx('you just got some response');
</script>

当您只需要重新加载 parent.html 时,它会更容易一些。

再次在parent.html和child.html中设置document.domain-property(parent.html和dispatcher.html中不需要iframe)

在 parent.html 中还设置了窗口的名称属性,例如

<script>
window.name="parentTab";
</script>

在 child.html 中,您现在可以访问 parentTab-window(tab)

<script>
document.domain="mydomain.com";
window.open('http://www.mydomain.com/parent.html','parentTab');
</script>

...或者简单地使用“parentTarget”作为 child.html 中链接或表单的目标属性

关于javascript - 如何将事件从子窗口发送到其父窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13334204/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com