Display a window.confirm alert to prevent any unauthorized changes to the URL

Looking to implement a feature that prevents changing the URL from my component. The goal is to display a message and allow users to choose between canceling (no change to URL) or confirming (change the URL). How can I achieve this in the upcoming 13.4 version?

I have tried implementing the following logic, but it seems to not be functioning as expected. The window.confirm message does not appear.

useEffect(() => {
  const handleBeforeUnload = (event: BeforeUnloadEvent) => {
    const mess = window.confirm('Are you sure you want to leave?');
    event.returnValue = mess;
    if (!mess) {
      event.preventDefault();
    }
  };

  window.addEventListener('beforeunload', handleBeforeUnload);

  return () => {
    window.removeEventListener('beforeunload', handleBeforeUnload);
  };

Answer №1

This code snippet has proven to be effective for me, even when I tested it within the StackOverflow environment.

window.addEventListener('beforeunload', function (event) {
  const unsavedChanges = true;
  if (unsavedChanges) {
    const confirmationMessage = 'You have unsaved changes. Are you sure you want to leave?';
    event.returnValue = confirmationMessage;
    return confirmationMessage; 
  }
});
<button onclick="window.location.href = 'https://example.com/'">Go to example.com</button>
<button onclick="window.location.reload()">Reload</button>

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

Issue with Next.js version 13 preventing export functionality

When running next build with the version "next": "^13.2.4", the expected "export" folder does not appear in the ".next" directory. The output: 'export' is set in the next.config.js. However, running next build on the canary ...

Encountering a JavaScript error due to an erroneous character when trying to parse

I need to convert a `json` string into an object format that is extracted from a `.js` file. Here is the `JSON` string located in `document.js`: [ { "type": "TableShape", "id": "63c0f27a-716e-804c-6873-cd99b945b63f", "x": 80, ...

Is there a way to display a Google Map marker after a certain amount of time without needing to refresh the

Is it possible to update Google Map markers without refreshing the map itself every 30 seconds? The markers' latitudes and longitudes are retrieved from a database. Once obtained, these markers are then allocated onto the Google Map. However, the i ...

Mozilla browser experiencing issues with mouse move event functionality

Here, I have a background image on the body and with the following script, when the user moves the mouse, the image in the background also moves. body { background-image: url('../images/1.png'); background-size: 98%; background-posi ...

The global variable remains unchanged after the Ajax request is made

I am attempting to utilize AJAX in JavaScript to retrieve two values, use them for calculations globally, and then display the final result. Below are my code snippets. // My calculation functions will be implemented here var value1 = 0; var v ...

Tips for verifying the contents of a textbox with the help of a Bootstrap

I am still learning javascript and I want to make a banner appear if the textbox is empty, but it's not working. How can I use bootstrap banners to create an alert? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&g ...

Receive an HTTP POST request within JavaScript without using Ajax in Symfony 4.1

Searching for a way to handle an event triggered by a PHP post, not through Ajax. I would like to show a spinner when the form is posted using PHP. In JavaScript, it's easy with code like this: $(document).on({ ajaxStart: function() { $('#p ...

Setting a port in Next.js: A step-by-step guide

I have one application currently running on port 3000 and I need to run another application on a different port in React Next.js. How can I make this change? In my package.json file, the current scripts section looks like this: "scripts": { & ...

Enhancing performance by dynamically updating DOM elements when they come into view during scrolling

Currently, I am in search of an efficient algorithm to dynamically load background-images for a group of <li>'s but I am encountering some efficiency issues. The code I am using at the moment is as follows: function elementInView($elem, vps, vp ...

Positioning the div to align perfectly alongside the list items

My current objective involves dynamically creating div elements and populating them with items. A working demo of my progress can be found by following this link. The issue at hand is that the newly created div does not appear in the desired location, but ...

Show the comment section only if the initial radio button is selected

I am struggling to implement a comment section that is displayed when the first radio button is checked. Here's the code I have tried: I attempted the following to show the section and test the associated script: <div id="commentaryDiv" ...

$filter is functioning correctly, however it is generating an error message stating: "Error: 10 $digest() iterations reached. Aborting!"

Here is an example of a JSON object that I am working with: { "conversations":[ { "_id": "55f1595d72b67ea90d008", "topic_id": 30, "topic": "First Conversation", "admin": "<a href="/cdn-cgi/l/e ...

Flipping over every single card, but only desire to flip them one at a time

My attempt to flip these cards individually has resulted in them all flipping together. I suspect there may be an error in my JavaScript code. In the original code, I used images in front and an unordered list in the back, but here I have simplified it t ...

Issues with Rock Paper Scissors Array in Discord.js V12 not functioning as expected

I'm currently working on implementing an RPS game in my Discord bot. I want to create a feature where if the choice made by the user doesn't match any of the options in the list, it will display an error message. Here is the code snippet that I h ...

Comprehending the "fitBounds" Function in Google Maps

Just to clarify, I want to ensure that my understanding is correct. In my Google Maps app, I want to display markers from specific continents to my users. Question: Is it accurate to say that a boundary in the Google Maps API is an area defined by NO MORE ...

Obtaining the value of an input field in HTML

I am currently working on a text input field that triggers a JavaScript function when a numeric value is entered. <input type="text" value="key" ng-keypress="submit(key)" ng-model="pager.page"/> Controller $scope.submit = function (val) { ...

In the dragstart event handler, event.dataTransfer and event.originalEvent will consistently be null

I have been working on developing drag and drop directives for angularJS by referencing this informative post: However, I am facing an issue where the dataTransfer and originalEvent are consistently null within the dragstart event handler, preventing me f ...

Issue with firebase.auth() method not triggering onAuthStateChanged after user login/logout操作

My code looks like this: var config = { apiKey: "xxxxx", authDomain: "xxxxx", databaseURL: "xxxxx", projectId: "xxxxx", storageBucket: "xxxxx", messagingSenderId: "xxxxx" }; firebase.initializeApp(config); $("#l ...

Tips on showcasing the elements within a div container using flexbox

Seeking advice on positioning items/cards using flexbox in my initial react app. The issue lies with the div within my card component where applying display: flex; turns every card into a block (column-like) structure, flexing only the content within each ...

Completing Forms with KendoUI Autocomplete

I am currently working with a KendoUI Autocomplete feature within a <form>. One issue I have encountered is that if the user presses the enter key while the autocomplete options are displayed, it only closes the options without submitting the form. S ...