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

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

对此,个人解决方案是经过window.open的方式来解决。dom

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

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

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

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

如下是chromeWindowShowModalDialog.jscode

 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 }

 

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

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

 

父窗口的回掉函数blog

function doChromeWindowShowModalDialog(obj){
    if(obj!=null){
      //TODO
    }
}
相关文章
相关标签/搜索