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 } }