What methods is Facebook using to manage their onbeforeunload confirmation dialog?

While using Facebook on the latest Chrome browser on my Mac, I observed an interesting behavior. When I began typing in a comment box and then clicked on another link or pressed the back button, a confirmation window popped up asking if I wanted to leave:

As a seasoned developer, I always thought that the only way to handle such situations was by attaching an onbeforeunload event to the page. I knew you could simulate onbeforeunload with a global binding on anchors, but I was surprised to see Facebook's custom-styled confirmation instead of the usual bland one.

I wonder how they achieved this. Could it be related to HTML5 window history or pushState events?

Answer №1

Hey there! I stumbled upon this solution on Stackoverflow over here.

This particular code snippet deals with the onbeforeunload event.
To experiment with this in your own browser, simply type the following into your console:

window.onbeforeunload = function() { return "Your work will be lost."; };

Then hit enter and test out the back button.

Now onto the actual solution:

Based on what I've tested, Facebook handles the situation of pressing the back button as described above, along with the cancelling of a comment by clicking on another link that triggers a div to appear on the page.

Edit

If we could somehow prevent the browser from navigating away from the AJAX context, this method might do the trick (enter it in the console):

window.onpopstate = function (event) {
 alert("location: " + document.location);
 event.preventDefault();
 return false;
}

I chose to share my insight here because unlike Facebook, this platform doesn't employ such functionality by default – which was your original query. But I do hope someone comes forward to challenge this!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using javascript, how can you fill in the missing dates within an array of objects?

I need to populate this object with dates starting from today up to the next 7 days. Here is my current object: let obj = { "sessions": [{ "id": 0, "available_capacity": 3, "date": "15-05- ...

Next.js application experiencing unexpected behavior with React state update and useEffect

Encountering unexpected behavior with state updates and useEffect in my Next.js app. The lock/unlock feature in a component is not functioning as intended. Below is the relevant code snippet: const [isLocked, setIsLocked] = useState(false); useEffect(() = ...

Changing camera view in Three.js upon clicking an HTML button

My goal is to create a straightforward animation using three.js, HTML, and CSS. The concept involves generating multiple BoxGeometries within a for loop and adjusting the rotation of each box incrementally with each iteration. I have successfully achieved ...

Displaying a dynamic map with real-time coordinates sourced from a database using a combination of ajax and php

I'm currently facing an issue where my solution to retrieve coordinates for a specific place from a database and display a map centered on them is not working as expected. The problem seems to be arising because the map is being initialized without an ...

Completely triggering a forced refresh on a single page application, disregarding cache, service workers, and all other

After experimenting with service workers on my Vue-built website, I made a critical error that has left Safari on my iPhone displaying only a blank page. To troubleshoot the issue, I connected my phone to my Mac and utilized Safari's inspector tool t ...

jQuery.get() function is limited to specific types of webpages

I have successfully combined multiple weather APIs on my website, which can be found here. Recently, I started using the weather.gov API and it has been quite effective. However, there are certain data points that I need to extract which the weather.gov A ...

Function that returns an Observable<Boolean> value is null following a catch block

Why is the login status null instead of false in this method? // In the method below, I am trying to return only true or false. isLoggedIn(): Observable<boolean> { return this .loadToken() .catch(e => { this.logger ...

3D Object Anchored in Environment - Three.js

In my current scene, I have two objects at play. Utilizing the LeapTrackballControls library for camera movement creates a dynamic where one object appears to rotate based on hand movements. However, an issue arises as the second object also moves along w ...

What impact does adding 'ng' in unit tests have on how promises are handled?

Here is an example of a service that utilizes $q.when to wrap a promise from a third-party library: // myService.js angular.module('myApp', []) .service('myService', function($q, $window) { var api = new $window.MyAPI(); this ...

Transmit responses from PHP script

I am in the process of creating a signup form where, upon clicking the submit button, all form data is sent to a PHP file for validation. My goal is to display an error message next to each input field if there are multiple errors. How can I achieve this ...

Switch the jQuery overlay image upon clicking a button

Is there a way to dynamically change the overlay image of a jQuery-ui dialog using a button click from inside the dialog? I attempted to do so in the code snippet below, but unfortunately, the overlay image does not update. It seems that I need to manipu ...

Creating a query string using a jQuery array that contains multiple values for a query variable

After writing some code to convert an array into a filter string, I noticed that the generated string was not in the format I wanted. product_size=123&product_size=456 Instead of this, I needed it to be product_size=123+456. To achieve this, I reali ...

The MUI Theming feature with primary color set to light seems to be causing confusion with the light color property

Trying to grasp the concept of MUI theming. There is a section dedicated to theming where it mentions the ability to change the theme. My query is: Within the primary color, there are three colors that can be defined: main, dark, and light. I'm unsur ...

Mastering Cookies in Javascript

I have been exploring the world of cookies in Javascript and decided to create an experimental log-in page. The page is fully functional, but I am interested in displaying the user's username and password using cookies. Is this possible with Javascrip ...

Fill up a dropdown menu in HTML when clicking on it

My webpage has multiple HTML select dropdowns that need to be populated onclick of the element. To achieve this, I use an AJAX call in the click event listener of the select elements. The decision to populate on click is driven by the importance of perfor ...

Sending information between two Angular 7 applications

I have a challenge where I need to pass data between two Angular applications that are running on different domains. Despite my attempts to use window.postMessage, I am unable to successfully transfer data to the second application. The first application ...

Running the command Yarn build with Vite.js and React.js is encountering issues and is not functioning properly

Lately, I've been experimenting with Vite in my React projects. However, when I execute the command yarn build, it creates a Build folder but the application fails to work. When I open the index.html file, all I see is a blank page. Interestingly, e ...

ReactJS mixes up fetch URLs with another fetch_WRONG_FETCH

I have a fetch function in my Home component: export default function Home() { const { rootUrl } = useContext(UserContext); useEffect(() => { fetch(`${rootUrl}/api/products/featuredProducts`) .then((result) => result.json()) .then ...

The Bcrypt hashed password does not match the password hash stored in Mongodb

When I use bcrypt.hash to encrypt a password, the hash generated is normal. However, when I save this hashed password in MongoDB using Mongoose, it appears to be different from the original hash. For example: Password hash: $2b$10$bUY/7mrZd3rp1S7NwaZko.S ...

Tips for preloading an ENTIRE webpage

I am looking for a way to preload an entire web page using JavaScript in order to have it cached in the user's browser. While I know how to preload images with JS, my goal is to also preload the entire page itself. For example, on my website, there ...