Prevent displaying page confirmation prompts when a user clicks on hyperlinks

One way to display a confirmation message when a user tries to leave the current page is by using this method:

window.addEventListener("beforeunload", function (e) {
              var confirmationMessage = "Are you sure you want to leave?";

              e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
              return confirmationMessage;              // Gecko, WebKit, Chrome <34
        });

This also applies to clicking on links, which is expected behavior as it involves leaving the page.

Is there a specific Javascript technique to prevent this confirmation message from appearing when clicking on hyperlinks, similar to what other websites have implemented?

Answer №1

In order for the confirmation to appear, make sure that e.returnValue is not an empty string. It's important to check which object triggered the event and set the value accordingly:

   window.addEventListener("beforeunload", function (e) {
          var confirmationMessage = "";

          // Check if the target of the event is not a link
          if(e.target.nodeName !== "A"){
              confirmationMessage = "Are you sure?";
          }

          e.returnValue = confirmationMessage;     // Supported in Gecko, Trident, Chrome 34+
    });

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

Polymer event / callback for appending new child nodes

My current project involves creating a custom element, let's call it <parent-element>, that performs specific actions based on the presence of its childNodes. When I define the element like this: <parent-element> <div> </div&g ...

What are the steps to integrate HJSON with Jest in a create-react-app development environment?

Currently, I am utilizing HJSON within a create-react-app project (view answer here). However, Jest does not utilize the same webpack configuration, resulting in a failed import of HJSON - for instance, import options from '../assets/options.hjson&ap ...

What sets apart "config" from "defaults" in Sencha Touch?

As a newcomer to Sencha Touch, I have one simple question that's been on my mind... Can someone explain the distinction between "config" and "defaults" in Sencha Touch? ...

Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when t ...

What function does this array serve following the object that was returned?

Could someone explain the usage of [this.props.currency] at the end of the return object, or direct me to a resource where I can learn more about this coding pattern as it is unfamiliar to me. I am not inquiring about the definition of this.props.currency ...

Is it possible to transform all values in arrays to 0s in JavaScript/p5.js during the copying process?

I’m struggling with a simple code where I want to store an array of arrays containing FFT audio data. It seems like there might be a JavaScript issue because when I try to push the array into another array called spectrums, all the values inside spectr ...

What is causing my animation to jump when using the Web Animation API reverse() function?

I've come across various sources stating that when you call reverse() while an animation is playing, it should have the same effect as setting playbackRate to -1. However, in my case, using reverse() makes my animation behave erratically and jump arou ...

What is the best way to iterate through one level at a time?

Imagine a scenario where the structure below cannot be changed: <xml> <element name="breakfast" type="sandwich" /> <element name="lunch"> <complexType> <element name="meat" type="string" /> <element name="vegetab ...

Modifying the style of a specific row when the form is submitted

My webpage contains nested records, with each nested record displaying a total number of clicks in a div labeled "count". I am looking to increment the count by 1 for each specific record when the button with a class of view is clicked. Currently, clicking ...

Mirror Image Iframes

Currently, I have been tasked with constructing a side-by-side "frame" using HTML. The idea is that when the content in the iframe on the left is selected, it will appear in the iframe next to it on the same page. Here's some additional context: The ...

Using Ajax for updating table content on a JSP webpage section

I am working on implementing Ajax functionality for a table to enable partial updates every hour. Below is a snippet of my JSP code: < head > < meta http - equiv = "Content-Type" content = "text/html; charset=ISO-8859-1" > < titl ...

Adding an existing element to the DOM using Javascript/jQuery

I am facing an issue in my DOM where I have an element with two children, a div block and a button. My goal is to add a new copy of the same div block to the parentNode whenever the button is clicked. Currently, I am using the following code in the button ...

Error encountered at / - undefined local variable or method `parameters' for main:Object (Executing Stripe Charge with Stripe.js)

Encountering an error with the code below while attempting to create a Stripe charge using Stripe.js. Below is my web.rb file: require 'json' require 'sinatra' require 'sinatra/reloader' require 'stripe' get &a ...

Attempting to increase a variable by 1, only to find that it appears to be doubling on its own

As I work on developing a quiz, I encounter an issue with my code. When I click on the question_holder div, variable x seems to be doubling instead of incrementing as expected. The value of x is supposed to increase by one each time, but it appears to ski ...

In Express.js, the value of req.body.data is not defined

Recently, I've been delving into nodejs and express js. My aim is to send a json object to my nodejs application using postman. Below is the code snippet from my app: var express = require("express"); var bodyParser = require('body-parser') ...

Function in Typescript that can return multiple data types

I recently started learning about TypeScript and its concepts. During my practice sessions, I encountered a problem that left me puzzled. There is a function named `functionA` which returns an object based on the response received from an API. type Combina ...

Errors that occur when parsing templates in Angular 2

I'm encountering a template parse error with my Angular 2 component using the following template: <div *ngIf="chapter == 1"> <p><h4><br><b>Exercise</b>: Get the Groceries starting point<br></h4 ...

Error message indicating unauthorized access while trying to implement Backbone with Slim framework and Tuupola basic authentication

I've been working on connecting my Backbone app with my server API (using Slim) and have implemented Tuppola / Basic Auth Middleware to handle authentication. The setup is fairly simple, as I'm just trying to make it work. When I access the serv ...

Creating a layout of <video> components in vue.js, complete with the ability to rearrange and resize them through drag and drop functionality

Despite trying numerous libraries and Vue.js plugins, I have yet to find one that meets all of my requirements. I am in need of creating a grid of video HTML elements that are draggable and resizable with a consistent aspect ratio of 16:9. Additionally, I ...

I am looking to dynamically insert a text field into an HTML form using jQuery or JavaScript when a specific button is clicked

This is my code snippet: <div class="rButtons"> <input type="radio" name="numbers" value="10" />10 <input type="radio" name="numbers" value="20" />20 <input type="radio" name="numbers" value="other" />other </div> ...