【问题标题】:Passing Data from Parent Window of One domain to Child window of another domian将数据从一个域的父窗口传递到另一个域的子窗口
【发布时间】:2011-05-16 05:56:57
【问题描述】:

我有两个域,分别是 X 和 Y,它们都位于具有不同 IP 的不同服务器上。

现在的情况是,在域 X 的一个页面上,有一个链接可以打开域 Y 的弹出窗口。

用户在该弹出窗口中搜索一些数据,然后点击“完成”

单击时,与搜索字段相关的值应传递到域 X 上的页面。

我为此使用 PHP、HTML 和 js。

P.S.:域名相同的情况下可以解决,但我想要域名和服务器不同的解决方案。

【问题讨论】:

标签: javascript html webforms parent-child


【解决方案1】:

我只想补充一点,可能通过window.name 属性将数据从一个域的窗口传递到另一个域的窗口。当然,这个属性不是为此目的而设计的,语言纯粹主义者会因此而恨我。尽管如此,这就是它的完成方式,又快又脏:

在域 X 上:

var PREFIX = "your prefix here";
// The second parameter of window.open() sets window.name of the child window.
// Encode JSON and prepend prefix.
window.open("http://domain-y.example.com/", PREFIX + JSON.stringify({"foo":"bar", "abc":123}));

在域 Y 上:

var PREFIX = "your prefix here";
if(window.name.substr(0, PREFIX.length) == PREFIX){
    // Remove prefix and decode JSON
    var data = JSON.parse(window.name.substring(PREFIX.length));
    // Do what you need to do with the data here.
    alert(data.foo); // Should alert "bar"
}

PREFIX 是可选的,但我更喜欢包含它,以防域 Y 被设置window.name 属性的其他页面访问。另请注意,您不需要使用 JSON(如果您使用的是恐龙浏览器,则不应该使用 JSON),但我喜欢 JSON,因为我可以在一个对象中传递多个属性。

编辑:如果您需要域 Y 将数据传回域 X,您可以让域 Y 将数据保存在 window.name 并导航到域 X 上的传递者页面,该页面可以轻松地将数据传递到原始窗口。试试这个:

在域 Y 上:

// Somewhere earlier in the code:
var PREFIX = "your prefix here";
// Call this function when the Done button is clicked.
function passDataBack(data){
    window.name = PREFIX + JSON.stringify(data);
    window.location = "http://www.domain-x.com/passer.html";
}

http://www.domain-x.com/passer.html:

// Somewhere earlier in the code:
var PREFIX = "your prefix here";
if(window.name.substr(0, PREFIX.length) == PREFIX){
    // Remove prefix and decode JSON
    var data = JSON.parse(window.name.substring(PREFIX.length));
    // Send data to parent window
    window.opener.processData(data);
}

在原始页面中,应该有一个名为processData 的函数,它获取数据并对其进行处理。

【讨论】:

  • 这是一个很棒的 hack。我在生产中使用它没有任何问题。
【解决方案2】:

你需要调查

CORS(对于较旧的 IE,您需要 XDR)或

window messaging

JSONP

通过 url 发送变量

【讨论】:

  • 我正在阅读它,虽然演示代码真的很可观
  • 到处都有演示。首先弄清楚您要使用哪种技术。很抱歉,我没有时间粘贴 4 个示例或从头开始编写一些示例,因为我需要两个域/子域上的代码。如果您对两个域上的代码都有完全访问权限,请尝试 CORS。
  • 好的,谢谢,我会尝试 CORS 并检查它是否可以解决我的问题
  • CORS 真的很简单。您只需要在服务器 B 上返回一些 headers 以允许服务器 A 访问内容。
【解决方案3】:

我知道这是一个老问题,但我认为这可能是对这个问题的更合适的答案

您应该将以下代码添加到 http://domain-x.com

window.addEventListener("message", function(event) {
  console.log(event.data); // {user: 'data'}
}, false);

... http://domain-y.com

userClicksDone() {
  try {
    // This may throw an error in case of people access
    // http://domain-y.com directly, not via popup from
    // http://domain-x.com
    //
    window.opener.postMessage({user: 'data'}, 'http://domain-x.com');
  } catch(e) { }

  // Closes this popup
  //
  window.close();
}

更多信息请访问Mozilla。 感谢@mplungjan

【讨论】:

    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    相关资源
    最近更新 更多