How can I implement a pop-up that activates when a reader tries to close the browser tab or window using JavaScript in Webflow?

TL;DR
  • Add a beforeunload JavaScript event in the Custom Code section of Webflow's settings to trigger a pop-up on tab close or window exit.
  • Customize the pop-up message text via the confirmationMessage variable, and test across browsers to understand appearance variations due to security restrictions.

Implementing a pop-up that activates when a reader tries to close the browser tab or window can be achieved in Webflow using custom JavaScript. 

1. Add Custom Code to Trigger Pop-Up

  • Go to Project Settings in your Webflow dashboard.
  • Navigate to the Custom Code tab.
  • In the Body tag section, add the following code snippet to trigger a pop-up using the beforeunload event:

  ```javascript

  window.addEventListener('beforeunload', function (e) {

    var confirmationMessage = 'Are you sure you want to leave?';

    e.returnValue = confirmationMessage; // Standard way to display a dialogue in some browsers.

    return confirmationMessage; // For older browsers.

  });

  ```

  • Save the changes and Publish your project to see it live.

2. Customize the Pop-Up Message

  • The default beforeunload prompt is browser-specific and cannot be customized with your own content or styling.
  • Focus on the confirmationMessage variable within the event to customize the message text shown.

3. Test the Pop-Up

  • Publish your site and open it in a new browser tab.
  • Attempt to close the tab or navigate away to test whether the pop-up works as expected.

4. Considerations and Limitations

  • Modern browsers offer limited customization for this type of pop-up for security reasons.
  • The appearance and exact message might differ from browser to browser.
  • Test on multiple browsers to understand how it behaves.

Summary

To implement a pop-up in Webflow that activates on tab close or window exit, utilize the beforeunload JavaScript event in the Custom Code section of your project settings. Remember that modern browser limitations restrict customization beyond a simple message prompt.

Rate this answer

Other Webflow Questions