【问题标题】:code after window.alert not executing when additional dialog boxes prevented当阻止其他对话框时,window.alert 之后的代码未执行
【发布时间】:2016-02-14 22:28:23
【问题描述】:

在 firefox 38 中,我注意到如果我激活浏览器的反弹出功能,它会停止执行在调用 window.alert()window.confirm() 之后的行上的代码

例如,给定代码:

var cb = document.querySelector("input");
cb.onclick = function(){
    console.log("before alert");
    window.alert("foo");
    console.log("after alert");
};
<center><input type=checkbox></center>

如果您多次点击复选框,每次点击之间的间隔不到 3 秒,那么在弹出窗口中您将可以选择“阻止此页面创建其他对话框”。激活它。完成后,您会看到警报停止执行后的console.log。

这是一种预期的 Firefox 行为吗?它记录在哪里?

Chrome 不会以这种方式运行 - 它仍会执行 window.alert() 行之后的代码。

编辑 - 我发现了一个错误报告:https://bugzilla.mozilla.org/show_bug.cgi?id=633154。似乎在某些版本中,如果警报被抑制,它们会抛出 NS_ERROR_NOT_AVAILABLE 异常,但在某些版本中它们不会并且它是静默的。

【问题讨论】:

  • 我的 Firefox 是 44 岁,并且在检查弹出警报中的阻止警报复选框后,我也可以正常获取两个控制台日志,尝试将您的 Firefox 更新到最新版本
  • @Armen 你是对的,v44 表现正常。 v38、40,我认为 42 也以这种奇怪的方式表现。
  • 如果它是一些重要的警报/确认消息,您可以改为默认使用一些现成的弹出窗口,其中有很多:defunkt.io/faceboxfancybox.net 或选择其中一个 codegeekz.com/jquery-modal-plugins 等。并实现ok cancel 按钮,里面有callbacks,所以它会在不同的浏览器下以相同的方式表现

标签: javascript firefox popup


【解决方案1】:

没有发现任何关于这种奇怪警报行为的提及。 HTML5 规范。只说一般:

...用户代理可能会为用户提供忽略所有警报的选项...

我建议将警报包装到 try/catch 块中,使其行为“标准”:https://jsfiddle.net/zvtam8ur/6/

function myAlert(message) {
  try {
    window.alert(message);
  } catch (e) {
    console.log("alert error!");
  }
}

var cb = document.querySelector("input");
cb.onclick = function(){
  console.log("before alert");
	myAlert("foo");
  console.log("after alert");
};

【讨论】:

  • 这适用于某些版本。有时 firefox 会在警报被抑制时抛出异常,但在其他版本中它会静默失败。
【解决方案2】:

我已经在 Firefox 和 Google chrome 中尝试过。

里面没有这样的功能。

即使没有确认(此处给出示例)-

function myFunction() {
    var txt;
    console.log("before alert");
    var r = confirm("Press a button!");
    if (r == true) {
        txt = "You pressed OK!";
    } else {
        txt = "You pressed Cancel!";
    }
    console.log("after alert");
    document.getElementById("demo").innerHTML = txt;
}
<p>Click the button to display a confirm box and check your console log.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

在 Firefox 和 Chrome 中当然也不允许正常警报-

function myFunction() {
    console.log("before alert");
    alert("Hello! I am an alert box!");
    console.log("after alert");
}
<p>Click the button to display an alert box and check the console log.</p>

<button onclick="myFunction()">Try it</button>

我在 Firefox 和 Chrome 中的测试结果在 this youtube video 中给出。

为了看得更清楚,请像这样改变视频的速度-

希望你有完整的答案。

【讨论】:

  • 谢谢,在较新的 firefox 版本中,他们改变了行为。
猜你喜欢
  • 2016-05-27
  • 1970-01-01
  • 2015-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多