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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM