安卓手机的浏览器中使用alert()和confirm()时,弹出几次后就会出现关闭网页按钮,影响用户体验。本文主要介绍通JavaScript(JS)来重写移动端的alert()和confirm(),来实现去掉其中的关闭网页按钮。

1、提示窗口代码

代码是基于Bootstrap实现,需要引用Bootstrap的js和css。代码如下:

  function MsgAlert (options) {
	var deferredObject = $.Deferred();
	var defaults = {
		type: "alert", //alert, prompt,confirm 
		modalSize: 'modal-sm', //modal-sm, modal-lg
		okButtonText: '确定',
		cancelButtonText: '取消',
		yesButtonText: '是',
		noButtonText: '否',
		headerText: '提示',
		messageText: 'Message',
		alertType: 'default', //default, primary, success, info, warning, danger
		inputFieldType: 'text', //could ask for number,email,etc
	}
	$.extend(defaults, options);
	var _show = function(){
		var headClass = "navbar-default";
		switch (defaults.alertType) {
			case "primary":
				headClass = "alert-primary";
				break;
			case "success":
				headClass = "alert-success";
				break;
			case "info":
				headClass = "alert-info";
				break;
			case "warning":
				headClass = "alert-warning";
				break;
			case "danger":
				headClass = "alert-danger";
				break;
        }
		$('BODY').append(
			'<div id="MsgAlerts" class="modal fade">' +
			'<div class="modal-dialog" class="' + defaults.modalSize + '">' +
			'<div class="modal-content">' +
			'<div id="MsgAlerts-header" class="modal-header ' + headClass + '">' +
			'<button id="close-button" type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>' +
			'<h4 id="MsgAlerts-title" class="modal-title">Modal title</h4>' +
			'</div>' +
			'<div id="MsgAlerts-body" class="modal-body">' +
			'<div id="MsgAlerts-message" ></div>' +
			'</div>' +
			'<div id="MsgAlerts-footer" class="modal-footer">' +
			'</div>' +
			'</div>' +
			'</div>' +
			'</div>'
		);
		$('.modal-header').css({
			'padding': '15px 15px',
			'-webkit-border-top-left-radius': '5px',
			'-webkit-border-top-right-radius': '5px',
			'-moz-border-radius-topleft': '5px',
			'-moz-border-radius-topright': '5px',
			'border-top-left-radius': '5px',
			'border-top-right-radius': '5px'
		});
		$('#MsgAlerts-title').text(defaults.headerText);
		$('#MsgAlerts-message').html(defaults.messageText);
		var keyb = "false", backd = "static";
		var calbackParam = "";
		switch (defaults.type) {
			case 'alert':
				keyb = "true";
				backd = "true";
				$('#MsgAlerts-footer').html('<button class="btn btn-' + defaults.alertType + '">' + defaults.okButtonText + '</button>').on('click', ".btn", function () {
					calbackParam = true;
					$('#MsgAlerts').modal('hide');
				});
				break;
			case 'confirm':
				var btnhtml = '<button id="ezok-btn" class="btn btn-primary">' + defaults.yesButtonText + '</button>';
				if (defaults.noButtonText && defaults.noButtonText.length > 0) {
					btnhtml += '<button id="ezclose-btn" class="btn btn-default">' + defaults.noButtonText + '</button>';
				}
				$('#MsgAlerts-footer').html(btnhtml).on('click', 'button', function (e) {
						if (e.target.id === 'ezok-btn') {
							calbackParam = true;
							$('#MsgAlerts').modal('hide');
						} else if (e.target.id === 'ezclose-btn') {
							calbackParam = false;
							$('#MsgAlerts').modal('hide');
						}
					});
				break;
			case 'prompt':
				$('#MsgAlerts-message').html(defaults.messageText + '<br /><br /><div class="form-group"><input type="' + defaults.inputFieldType + '" class="form-control" id="prompt" /></div>');
				$('#MsgAlerts-footer').html('<button class="btn btn-primary">' + defaults.okButtonText + '</button>').on('click', ".btn", function () {
					calbackParam = $('#prompt').val();
					$('#MsgAlerts').modal('hide');
				});
				break;
		}
		$('#MsgAlerts').modal({ 
          show: false, 
          backdrop: backd, 
          keyboard: keyb 
        }).on('hidden.bs.modal', function (e) {
			$('#MsgAlerts').remove();
			deferredObject.resolve(calbackParam);
		}).on('shown.bs.modal', function (e) {
			if ($('#prompt').length > 0) {
				$('#prompt').focus();
			}
		}).modal('show');
	}
  _show();  
  return deferredObject.promise();    
}

2、调用方法

窗口样式有五种类型:default, primary, success, info, warning, danger

1)调用alert窗口

MsgAlert({type:"alert",
messageText: "提示信息内容",
alertType: "info"
}).done(function (e) {
alert(e);
});

2)调用confirm窗口

MsgAlert({type:"confirm",
messageText: "提示信息内容",
alertType: "info"
}).done(function (e) {
alert(e);
});

3、重写浏览器中alert()和confirm()

window.alert = function (message) {
MsgAlert({type:"alert",
      messageText: message,
      alertType: "info"
    }).done(function (e) {
     alert(e);
    });
}
window.confirm = function (message) {
MsgAlert({type:"confirm",
      messageText: message,
      alertType: "info"
    }).done(function (e) {
     alert(e);
    });
}

如果不用使用Bootstrap方式重写,也可以尝试下面方法解决提示窗口中有关闭网页按钮问题,代码如下:

var wAlert = window.alert;
window.alert = function (message) {
    try {
        var iframe = document.createElement("IFRAME");
        iframe.style.display = "none";
        iframe.setAttribute("src", 'data:text/plain,');
        document.documentElement.appendChild(iframe);
        var alertFrame = window.frames[0];
        var iwindow = alertFrame.window;
        if (iwindow == undefined) {
            iwindow = alertFrame.contentWindow;
        }
        iwindow.alert(message);
        iframe.parentNode.removeChild(iframe);
    }
    catch (exc) {
        return wAlert(message);
    }
}
var wConfirm = window.confirm;
window.confirm = function (message) {
    try {
        var iframe = document.createElement("IFRAME");
        iframe.style.display = "none";
        iframe.setAttribute("src", 'data:text/plain,');
        document.documentElement.appendChild(iframe);
        var alertFrame = window.frames[0];
        var iwindow = alertFrame.window;
        if (iwindow == undefined) {
            iwindow = alertFrame.contentWindow;
        }
        iwindow.confirm(message);
        iframe.parentNode.removeChild(iframe);
    }
    catch (exc) {
        return wConfirm(message);
    }
}