我只想补充一点,可能通过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 的函数,它获取数据并对其进行处理。