将 iframe url 参数动态传递给父 URL

时间:2021-03-07 23:44:06

标签: javascript html jquery iframe

我是 iframe 与父级交互的新手,所以让我用简单的术语解释我面临的问题:

我有一个带有 iframe 的网站。如何使用 JavaScript 或 jQuery 代码根据用户在 iframe 中点击的内容动态更改我的父 URL?

例如,如果我的父 URL 是 parent.com?page=1&currency=eur,那么我的 iframe 将自动为 iframe.com?page=1&currency=eur,但用户可以点击 iframe 内的另一个链接。如果用户单击链接并且 iframe src 更改为 iframe.com?page=another_page,我希望父 URL 动态更改为 parent.com/page=another_pageparent.com#page=another_page。换句话说,我将所有 iframe URL 参数传递给父级。

谁能帮我解决这个问题?

我可以完全控制父窗口,也可以向子窗口添加一些代码,但它们不在同一个域中。

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用 window.postMessage 实现跨 2 个不同域的父 iframe/子窗口之间的交互。

在你的情况下,由于你的孩子正在修改你的父母,你应该像这样在你的父页面上设置一个监听器

window.addEventListener("message", (event) => {
  if (event.origin !== "http://thisisyourchilddomain.com") // You must check for the sender's origin or your website could be exploited !!
    return;

  // do something
}, false);

在您的子页面中,您将调用方法 window.postMessage

parent.postMessage("hello there parent! please perform a redirect with the following params...", "http://thisisyourchilddomain.com");

请注意,这里的 parent 是一个全局变量,您可以从您的孩子那里访问。此外,您可以将对象传递给 postMessage({key:value}, ..)

的第一个参数

示例是从 window.postMessage (mozilla) 的链接中获取和修改的。