高版本Chrome兼容window.showModalDialog办法
由于showmodaldialog 不属于W3C标准,在新版本浏览器中不再受支持,我们需要使用window.open来自定义一个showmodaldialog 来代替。
将要打开模态框的主页面papa.html代码:
<!DOCTYPE html>
<html lang="zh">
<head>
<title>主页面</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
</head>
<body>
<input id="a"/>
<button onclick="callSon()">打开模态框</button/>
<fieldset>
<legend>子页面返回</legend>
<span id="content"></span>
</fieldset>
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.js"></script>
<Script type="text/javascript">
//定义一个全局变量判定是否原生支持showModalDialog方法
var has_showModalDialog = !!window.showModalDialog;
//当其不受支持时自定义window.showModalDialog
if(!has_showModalDialog){
window.showModalDialog = function(url,dialogArguments,features){
if(window.hasOpenWindow){
//避免弹出多个窗口
alert("您已经打开了一个窗口!请先处理它");
window.myNewWindow.focus();
return;
}
//因window.showmodaldialog 与 window.open 参数不一样,所以封装的时候用正则去格式化一下参数
if(features)
var features = "modal=yes,"+features.replace(/(dialog)|(px)/ig,"").replace(/;/g,',').replace(/\:/g,"=");
var left = (window.screen.width - parseInt(features.match(/width[\s]*=[\s]*([\d]+)/i)[1]))>>1;
var top = (window.screen.height - parseInt(features.match(/height[\s]*=[\s]*([\d]+)/i)[1]))>>1;
features+=',left='+left+',top='+top;//窗口居中
window.myNewWindow = window.open(url,"_blank",features);
window.hasOpenWindow = true;
//open()不支持传递参数,通过这种方式向子页面传递参数,因为打开页面速度远远慢于本方法执行速度,因而子页面总能获得传递的参数
if(dialogArguments)
window.myNewWindow.dialogArguments=dialogArguments;
//window.myNewWindow.moveTo(left,top);
}
}
//打开模态框
function callSon(){
url = 'son.html';
var sonStyle="dialogWidth:500px;dialogHeight:450px;help:no;resizable:no;center:yes;scroll:yes;status:no";
var param={val:document.getElementById("a").value?document.getElementById("a").value:"son"}
var val = window.showModalDialog(url,param,sonStyle);
//chrome 返回 因为IE下showModalDialog是阻塞的 open不一样;
if(!has_showModalDialog) return;
afterCall(val);
}
//为打开的子窗口定义方法,让打开的窗口关闭时通过window.opener赋值回来并执行
function callSonChrome(val){
afterCall(val);
}
//获得模态框返回值后执行的业务方法
function afterCall(val){
$("#content").html(val);
}
</script >
</body>
</html>
被打开的模态框子页面son.html代码:
<!DOCTYPE html>
<html lang="zh">
<head>
<title>子页面</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
</head>
<body>
<input id="a"/>
<button onclick="closeToRetuen()">关闭模态框并返回</button>
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.js"></script>
<Script type="text/javascript">
var param = window.dialogArguments;
document.getElementById("a").value=param.val;
function closeToRetuen() {
var a = $("#a").val();
//chrome环境
if (window.opener != undefined) {
//关闭前调用父窗口方法返回需要返回的对象或字符串
window.opener.callSonChrome(a);
}
//ie环境
else {
window.returnValue = a;
}
window.close();
}
//页面关闭时主动通知调用页面我将关闭
window.onbeforeunload=function(){
window.opener.hasOpenWindow=false;
}
</script >
</body>
</html>
测试:
测试浏览器Google Chrome 版本 69.0.3497.100(正式版本) (64 位)
打开模态框
关闭模态框
参考文章: