因为项目是嵌套很多iframe的。弹窗口会有数据回传。弹窗之上又有弹窗也会有值回传。3级或者更多。所以我把兼容的js代码写在一个文件,所有涉及弹窗口的页面均调用这个脚本文件:
common.js
- var has_showModalDialog = !!window.showModalDialog;//定义一个全局变量判定是否有原生showModalDialog方法
- if(!has_showModalDialog &&!!(window.opener)){
- window.οnbefοreunlοad=function(){
- window.opener.hasOpenWindow = false; //弹窗关闭时告诉opener:它子窗口已经关闭
- }
- }
- //定义window.showModalDialog如果它不存在
- if(window.showModalDialog == undefined){
- window.showModalDialog = function(url,mixedVar,features){
- if(window.hasOpenWindow){
- alert("您已经打开了一个窗口!请先处理它");//避免多次点击会弹出多个窗口
- window.myNewWindow.focus();
- }
- window.hasOpenWindow = true;
- if(mixedVar) var mixedVar = mixedVar;
- //因window.showmodaldialog 与 window.open 参数不一样,所以封装的时候用正则去格式化一下参数
- if(features) var features = features.replace(/(dialog)|(px)/ig,"").replace(/;/g,',').replace(/\:/g,"=");
- //window.open("Sample.htm",null,"height=200,width=400,status=yes,toolbar=no,menubar=no");
- //window.showModalDialog("modal.htm",obj,"dialogWidth=200px;dialogHeight=100px");
- var left = (window.screen.width - parseInt(features.match(/width[\s]*=[\s]*([\d]+)/i)[1]))/2;
- var top = (window.screen.height - parseInt(features.match(/height[\s]*=[\s]*([\d]+)/i)[1]))/2;
- window.myNewWindow = window.open(url,"_blank",features);
- }
- }
执行弹出的当前页的方法用例:(有返回值)
- function selectHotel(){
- url = 'hotel/listHotelForChoose.action';
- var hotelIdList = window.showModalDialog(url, "hotel", "dialogWidth:1020px;dialogHeight:500px;help:no;resizable:no;center:yes;scroll:yes;status:no");
- if(!has_showModalDialog) return;//chrome 返回 因为showModalDialog是阻塞的 open不一样;
- $("#content").append(hotelIdList);
- }
- function selectHotelChrome(option){//为打开的窗口定义方法,让打开的窗口关闭时通过window.opener赋值回来并执行
- $("#content").append(option);
- }
子窗口这样调用:
- function chooseHotels() {
- /*
- *省略了自己的业务.......
- */
- if (window.opener != undefined) { //forchrome
- window.opener.selectHotelChrome(contentIds); //关闭前调用父窗口方法
- }
- else {
- window.returnValue = contentIds;
- }
- window.close();
- }