【问题标题】:HTML / Javascript Check window close and execute function [duplicate]HTML / Javascript检查窗口关闭并执行功能[重复]
【发布时间】:2015-11-21 22:47:18
【问题描述】:

我正在检测以这种方式关闭的窗口,它可以工作,但我无法执行功能。

function myFunc(){
   alert("byebye");
}
window.onbeforeunload = function (event) {
    myFunc(); //Error, it doesn't execute
    return "Bye"; //It works, it shows an alert.
};

关闭窗口/选项卡时如何调用 myFunc?

【问题讨论】:

    标签: javascript html function events


    【解决方案1】:

    通过用 return 替换 alert 来试试这个。

    function myFunc(){
       return "byebye";
    }
    window.onbeforeunload = function (event) {
        myFunc(); //Error, it doesn't execute
        return "Bye"; //It works, it shows an alert.
    };
    

    【讨论】:

      【解决方案2】:

      您不能在 onbeforeunload 事件中调用函数,您只能传递一个显示给用户的字符串。

      【讨论】:

      • 对不起 - 我太快了 - 你可以传递一个函数,但这个函数必须返回一个字符串。另见developer.mozilla.org/de/docs/Web/API/WindowEventHandlers/…
      • 如果我想要一个函数来修改 UI 而不是显示消息怎么办?我遇到了麻烦
      • 很遗憾,您只能在关闭窗口时显示一条消息。
      猜你喜欢
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 2010-12-19
      相关资源
      最近更新 更多