运行 关闭浏览器选项卡之前的一些 javascript 代码

running some javascript code before when you close a browser tab

我想 运行 一些 javascript 每当有人关闭浏览器选项卡但我不知道这怎么可能。

我尝试按照 所述进行操作,但它对我不起作用:

$(window).on('beforeunload', function() {
    return confirm("Do you really want to close?");
});

(已加载 jquery)

这是 JS fiddle:https://jsfiddle.net/hc9xrgvj/

有什么想法吗?

根据Mozilla

According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event.

However note that not all browsers support this method, and some instead require the event handler to implement one of two legacy methods:

assigning a string to the event's returnValue property
returning a string from the event handler.

Some browsers used to display the returned string in the confirmation dialog, enabling the event handler to display a custom message to the user. However, this is deprecated and no longer supported in most browsers.

To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all.

The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event.