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

源链接

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

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

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

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

showModalDialog方法打开的窗口是模态,而open不是。

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

以下是chromeWindowShowModalDialog.js

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

}
}

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

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

父窗口的回调函数

1
2
3
4
5
function doChromeWindowShowModalDialog(obj){
if(obj!=null){
  //TODO
}
}