You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firefox点击关闭按钮时window.onbeforeunload无提示问题求助

Fixing Firefox's window.onbeforeunload Not Triggering on Close Button Click

Hey there, let's work through why your onbeforeunload event isn't firing when clicking Firefox's close button, and fix it up.

First, let's spot the issue in your original code:

<body window.onbeforeunload="bunload">
function bunload() { dontleave = "Are you sure you want to leave?"; return dontleave; }

The core problem here is that onbeforeunload is a window-level event, not a <body> attribute. Binding it to the <body> tag won't work as expected in Firefox (or most modern browsers, for that matter).

Correct Implementation Steps

1. Bind the Event to the Window Object

You need to attach the beforeunload event directly to window, not <body>. Here are two reliable ways to do this:

Option 1: Direct Assignment (Simple)
// Assign the handler directly to window.onbeforeunload
window.onbeforeunload = function() {
  // Note: Modern browsers (including Firefox 44+) will ignore custom text
  // but returning a non-null/undefined value triggers the browser's default prompt
  return "Are you sure you want to leave?";
};
Option 2: Using addEventListener (Recommended for Multiple Events)

This method is better if you might need to attach multiple beforeunload handlers later:

window.addEventListener('beforeunload', function(event) {
  // Modern browser standards require both preventDefault() and setting returnValue
  event.preventDefault();
  event.returnValue = "Are you sure you want to leave?";
  return "Are you sure you want to leave?"; // Fallback for older browser versions
});

2. Key Notes for Firefox Compatibility

  • Custom Prompt Text: Firefox (and most modern browsers) no longer display custom text in the beforeunload prompt—they'll show a browser-native message instead. But you still need to return a non-empty value to trigger the prompt.
  • User Interaction Requirement: Firefox won't trigger beforeunload if the user hasn't interacted with the page (e.g., loading the page and immediately clicking close). This is a built-in anti-spam/anti-abuse measure—make sure you test after clicking somewhere on the page first.
  • No Async Operations: Don't include async code (like fetch calls) in the beforeunload handler—browsers won't wait for it to complete, so the prompt won't trigger.

Replace Your Original Code

Remove the window.onbeforeunload="bunload" from your <body> tag, and add one of the JavaScript snippets above (either in a <script> tag at the end of your <body> or in an external JS file).

That should get the prompt working when you click Firefox's close button, refresh the page, or navigate away!

内容的提问来源于stack exchange,提问作者prajna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:38:27