您的位置:首页 > Web前端 > JavaScript

JS实现跨域页面传值

2017-12-25 16:59 183 查看
一、背景介绍

页面1中有一个按钮,希望实现点击按钮打开页面2。

页面2进行一系列操作后,点击该页面确定按钮后关闭页面,同时返回值到页面1

ps:页面1与页面2位于不同服务器,即跨域

二、实现

使用postMessage()实现上述功能。

1.页面1上的代码:

//选择表单按钮的点击事件
selectFillForm : function(){
var self = this;
$("#selectForm").off('click');
$("#selectForm").on('click',function(){
window.open(url);//页面2的地址
});
}


//重写message事件以接受打开表单页面2返回的值
window.onmessage = function (e) {
var student = e.data;
if (student  != undefined && student  != null) {
if(student.id != undefined && student.id != null) {
var id = student.id;
var name = student.name;
......//后续具体操作代码
}
}

};


2.页面2上返回值代码

function onOk() {
var student= {name:"lily",id:1}
if (window.opener) {
window.opener.postMessage(student, '*');
}
window.close();
}


归纳实现操作就是:

1.页面1使用window.open(url)函数打开页面2

2.页面2使用window.opener.postMessage(param1,param2)返回消息到页面1;

3.页面1重写onmessage消息事件,获取返回值

注意:postMessage(p1,p2) 参数p1最早只能接受字符串,后来改成任何数据结构。可是,并非所有浏览器都实现这一变化。为了保险起见,最好使用JSON.stringify()转成字符串,然后在接收端的onmessage事件处理程序中使用JSON.parse();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript