Chrome浏览器showModalDialog兼容性及解决方案

chrome对showModalDialog方法是不兼容的,现在有年代久远的项目,是用的window.showModalDialog方式打开模态窗口,但现在提出有兼容性问题。

对此,我的解决方案是通过window.open的方式来解决。

1.showModalDialog方法的执行是阻塞的,而open不是。

showModalDialog好比是同步的,而open是异步,想要解决此问题,可以在子窗口中调用父窗口的方法把返回值传回去。

2.showModalDialog发打开的窗口是模态,而open不是。

没有找到此问题的完美解决方案,我所想的是在父窗口定义一个常量hasOpenWindow,打开窗口时将其改为true,当期为true时,将焦点定位在刚才打开的窗口而不去新建,在父窗口的回掉函数中再将此常量改为false。

以下是chromeWindowShowModalDialog.js

 1 /**
 2  * 打开方式对比:
 3  *     window.open("Sample.htm",null,"height=200,width=400,status=yes,toolbar=no,menubar=no");
 4  *     window.showModalDialog("modal.htm",obj,"dialogWidth=200px;dialogHeight=100px");
 5  *     因window.showmodaldialog 与 window.open 参数不一样,所以封装的时候用正则去格式化一下参数
 6  * 
 7  * 定义一个全局变量<has_showModalDialog>判定是否有原生showModalDialog方法
 8  * 如果它不存在,自定义window.showModalDialog
 9  * 
10  * if (window.opener != undefined && window.opener._doChromeWindowShowModalDialog) {
11  *         window.opener.__doChromeWindowShowModalDialog(tmplInfo);//for chrome
12  *     }else{
13  *         window.returnValue = tmplInfo;
14  *     }
15  */
16 var has_showModalDialog = !!window.showModalDialog;
17 if(window.showModalDialog == undefined){
18     window.showModalDialog = function(url,mixedVar,features){
19         if(window.hasOpenWindow){
20             window.myNewWindow.focus();
21             return;
22         }
23         window.hasOpenWindow = true;
24         if(mixedVar) var mixedVar = mixedVar;
25         if(features) var features = features.replace(/(dialog)|(px)/ig,"").replace(/;/g,',').replace(/\:/g,"=");
26         var left = (window.screen.width - parseInt(features.match(/width[\s]*=[\s]*([\d]+)/i)[1]))/2;
27         var top = (window.screen.height - parseInt(features.match(/height[\s]*=[\s]*([\d]+)/i)[1]))/2;
28         url = url + "&temp=" + Math.random();
29         window.myNewWindow = window.open(url,"_blank",features);
30     }
31 }
32 function _doChromeWindowShowModalDialog(obj){
33     window.hasOpenWindow = false;
34     try {
35         doChromeWindowShowModalDialog(obj);
36     }catch(e){
37         
38     }
39 }

 

 子窗口点击确定或者关闭时:

if (window.opener != undefined && window.opener._doChromeWindowShowModalDialog) {
  //for chrome
  window.opener._doChromeWindowShowModalDialog(tmplInfo);
}

 

父窗口的回掉函数

function doChromeWindowShowModalDialog(obj){
    if(obj!=null){
      //TODO
    }
}

 

posted @ 2017-01-04 15:02  jackkke  阅读(23425)  评论(0编辑  收藏  举报