公司的老项目都是使用的window.showModalDialog()这种方式实现的打开窗口,并且项目里的提示语均使用的alert和confirm等浏览器自带方法,但业务发展需要使用chrome,并且时间短原项目业务逻辑复杂,无法重构,只能改造。
showModalDialog
showModalDialog()此方法已在Chrome 43和Firefox 56中删除,为了在chrome里使用,用window.open()代替,涉及改造点:
- 窗口参数的传递 ,可用正则修改传参的格式;
- 父子窗口传参 将回调函数和初始参数;
- 窗口关闭的监听 循环监听关闭状态模拟原方法的阻塞进程;
- 窗口返回值 用object.defineProperty数据劫持获得;
重写方法
此处参考链接: https://blog.youkuaiyun.com/qq_38880340/article/details/82883110.
// An highlighted block
//定义一个全局变量判定是否原生支持showModalDialog方法
var has_showModalDialog = !!window.showModalDialog;
//当其不受支持时自定义window.showModalDialog
if(!has_showModalDialog){
/* url传入被打开网页的地址
* dialogArguments传入子页面需要的参数和判断参数:
* windowName4Open传入被打开网页的名称;
* callback4Open传入子窗口返回returnValue时的回调;
* autoCallback4Open用于打开的网页判断callback4Open是否存在
* features子网页的样式*/
window.showModalDialog = function(url,dialogArguments,features){
//新窗口的名字。如果该名字的窗口已经存在,则再次调用时占用该窗口,不再新建窗口。如果省略,(浏览器会)默认_blank
var name = dialogArguments.windowName4Open || '_blank';
if(name=='_blank' && window.hasOpenWindow){
//当窗口名为_blank时,再次调用不会占用未关闭的_blank子窗,需要手动避免弹出多个窗口
window.myNewWindow.focus();
return;
}
//因window.showmodaldialog 与 window.open 参数不一样,所以封装的时候用正则去格式化一下参数
if(features)
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,name,features);
//定义自动返回returnValue
if("function" === typeof dialogArguments.callback4Open /*其他条件*/){
//如果不冲突的情况下通过劫持子窗returnValue,达到无需在子窗手动执行回调的目的
dialogArguments.autoCallback4Open=true;
Object.defineProperty(myNewWindow, 'returnValue', {
get: function() {
//不需要写成window.myNewWindow.returnValue就可以
return returnValue;
},
set: function(value) {
returnValue = value;
//执行函数
dialogArguments.callback4Open(value);
}
});
}else{
Object.defineProperty(myNewWindow, 'returnValue', {});
}
window.hasOpenWindow = true;
if(dialogArguments){
//open()不支持传递参数,通过这种方式向子页面传递参数,因为打开页面速度远远慢于本方法执行速度,因而子页面总能获得传递的参数,
//也可在子窗load事件发生后使用myNewWindow.postMessage(dialogArguments,url),但在子窗还未load时监听可能无效,但它可以突破同源限制
window.myNewWindow.dialogArguments=dialogArguments;
}
//window.myNewWindow.moveTo(left,top);
}
}
上述代码基本可实现改造,但由于我公司项目的局限,在此基础做了其他的一点处理,将此改造作为公共js引入
解决点:
- 打开窗口父窗口产生遮罩层,点击遮罩层始终保证新开窗口focus;
- 新开窗口关闭后执行回调函数,关闭遮罩;
- 刷新父页面或者关闭父页面子窗口关闭;
做相应改造是因为遇到奇葩问题:点击遮罩子窗口focus时,若子窗口的操作有alert并且alert后面紧接着有关闭窗口事件,alert并未点击确定窗口就会被关闭。(想了好久查了很多资料,都是说最好不用alert,但目前系统全是alert,无奈只能用恶心的定时器,以及重写close的方式解决)
特殊改造
公共js—showModal.js
// An highlighted block
//定义一个全局变量判定是否原生支持showModalDialog方法
function isNative (fn) {
return (/\{\s*\[native code\]\s*\}/).test(fn + '')
}
//事件标准化函数
function getEventObject(W3CEvent) {
return W3CEvent || window.event;
}
// 设置样式
function css(targetObj, cssObj) {
var str = targetObj.getAttribute("style") ? targetObj.getAttribute("style") : "";
for (var i in cssObj) {
str += i + ":" + cssObj[i] + ";";
}
targetObj.style.cssText = str;
}
var has_showModalDialog = isNative(window.showModalDialog);
//当其不受支持时自定义window.showModalDialog
if(!has_showModalDialog){
// 原ie下不用加遮罩,也不会被改写
var $shadeBox = document.createElement('div')
css($shadeBox, {
"display": "none",
"position": "fixed",
" _position": "absolute",
" width": "100%",
"height": "100%",
"left": "0",
"top": "0",
"background": "rgba(0, 0, 0,0.5)",
"-moz-opacity": "0.5",
"filter": "alpha(opacity=50)",
"z-index": "97",
});
// 遮罩禁止右键
$shadeBox.oncontextmenu = function () {return false;}
// 整体显示到页面内
document.getElementsByTagName("body")[0].appendChild($shadeBox);
/* url传入被打开网页的地址
* dialogArguments传入子页面需要的参数和判断参数:
* callback4Open传入子窗口返回returnValue时的回调;
* features子网页的样式*/
window.showModalDialog = function(url,dialogArguments,features){
// 初始化劫持的returnValue,点击遮罩和子窗口focus和调用关闭事件的标志值
var dialog_returnVal,flagClick = 1,flagFocus = 1,flagClose = false;
//新窗口的名字。如果该名字的窗口已经存在,则再次调用时占用该窗口,不再新建窗口。如果省略,(浏览器会)默认_blank
var name = (dialogArguments && dialogArguments.winName) || '_blank';
if(name=='_blank' && window.hasOpenWindow){
//当窗口名为_blank时,再次调用不会占用未关闭的_blank子窗,需要手动避免弹出多个窗口
window.myNewWindow.focus();
return;
}
//因window.showmodaldialog 与 window.open 参数不一样,所以封装的时候用正则去格式化一下参数
if(features)
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,name,features);
if (!window.myNewWindow) {
alert("请设置浏览器允许弹窗")
return
}
// 特殊改造处
//1.监听子窗口关闭后回调
var loop = setInterval(function () {
if(myNewWindow.closed) {
if ("function" === typeof dialogArguments.callback4Open) {
setTimeout(function () {
dialogArguments.callback4Open(dialog_returnVal)
}, 0) // 关闭后再执行回调
css($shadeBox, {'display': 'none'})
$shadeBox.onclick = null
window.hasOpenWindow = false
clearInterval(loop)
}
}
}, 200)
//2.改造子窗口的关闭函数
myNewWindow._close = window.myNewWindow.close // 此处必须写myNewWindow._close 不能var _close
window.myNewWindow.close = function () {
flagClose = true;
var loopClose = setInterval(function () {
// 此处的判断依据是在子窗口被调用了close关闭且有alert时,点击遮罩只会触发遮罩的点击计算,子窗口的onfocus里的计算只会在alert点确定后才会触发,这样就可以达到监听alert点确定的效果了
if ((flagFocus == flagClick) || (flagFocus != flagClick && flagFocus != 1)) {
myNewWindow._close()
clearInterval(loopClose)
}
},200)
}
//3.监听子窗口focus并计算
window.myNewWindow.onfocus = function () {
if(flagClose) flagFocus += 1
}
//4.监听遮罩点击
//点击事件
var shade_click = function (e) {
// 阻止冒泡
getEventObject(e).stopPropagation ? getEventObject(e).stopPropagation() : getEventObject(e).cancelBubble = true
if (window.myNewWindow) {
window.myNewWindow.focus()
if(flagClose) flagClick += 1
}
}
$shadeBox.onclick = shade_click
//定义自动返回returnValue
if("function" === typeof dialogArguments.callback4Open /*其他条件*/){
//如果不冲突的情况下通过劫持子窗returnValue,达到无需在子窗手动执行回调的目的
dialogArguments.autoCallback4Open=true;
Object.defineProperty(myNewWindow, 'returnValue', {
get: function() {
//不需要写成window.myNewWindow.returnValue就可以
return returnValue;
},
set: function(value) {
returnValue = value;
//执行函数
dialog_returnVal = value
}
});
}else{
Object.defineProperty(myNewWindow, 'returnValue', {});
}
window.hasOpenWindow = true;
if(dialogArguments){
//open()不支持传递参数,通过这种方式向子页面传递参数,因为打开页面速度远远慢于本方法执行速度,因而子页面总能获得传递的参数,
//也可在子窗load事件发生后使用myNewWindow.postMessage(dialogArguments,url),但在子窗还未load时监听可能无效,但它可以突破同源限制
window.myNewWindow.dialogArguments=dialogArguments;
}
css($shadeBox, {'display': 'block'})
window.onbeforeunload = function () {
css($shadeBox, {'display': 'none'})
window.myNewWindow && window.myNewWindow.close()
}
}
}
可测试父页面-fa.html
// An highlighted block
<!DOCTYPE html>
<html lang="zh">
<head>
<title>主页面</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<style>
*{margin: 0px;padding: 0px;}
</style>
</head>
<body style="width:100vw;height:100vh;">
<input id="a"/>
<button onclick="callSon()">打开模态框</button/>
<h4>子页面返回</h4>
<div id="content"></div>
</fieldset>
<div id="result"></div>
<Script type="text/javascript" src="showModal_update.js"></script>
<script>
window.onload = function () {
css(document.getElementById('content'), {
'width': '500px',
'height': '32px',
'border': '1px solid red'
})
}
function callSon(){
url = 'son.html';
var sonStyle="dialogWidth:450px;dialogHeight:450px;help:no;resizable:no;center:yes;scroll:yes;status:no";
var param={
val: document.getElementById('a').value
}
param.callback4Open=callSonChrome;
var val = window.showModalDialog(url,param,sonStyle);
//chrome下返回不执行afterCall,而是作为回调(callSonChrome),因为IE下showModalDialog是阻塞的可以直接afterCall,open则是异步的;
if(!has_showModalDialog)
return;
afterCall(val);
}
//为打开的子窗口定义方法,让打开的窗口关闭时通过window.opener赋值回来并执行
function callSonChrome(val){
afterCall(val);
}
//获得模态框返回值后执行的业务方法
function afterCall(val){
document.getElementById('content').innerHTML = val;
}
</script>
</body>
</html>
可测试子页面-son.html
// An highlighted block
<!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 type="text/javascript" src="showModal_update.js"></script>
<script>
var param = window.dialogArguments;
document.getElementById('a').value = param.val
function closeToRetuen() {
alert('您返回的值是:'+document.getElementById('a').value)
window.returnValue = document.getElementById('a').value;
window.close();
}
</script>
</body>
</html>
测试数据劫持最好在服务环境下测试,简单的node服务----app.js
// An highlighted block
const express = require('express');//引入express框架
const app = express();
app.use(express.static("demo")).listen(8080);
第一次写,只是为了记录这个让人头疼的bug
参考文章
1.https://blog.youkuaiyun.com/qq_38880340/article/details/82883110.*