Display a modal when closing a tab using Vue.js

I'm attempting to display a confirmation popup when the page reloads or the user navigates outside of my website in Vue.js. I have already implemented the beforeRouteLeave function in my component, but it only works when navigating to another page within my site, not when leaving the site or reloading the page. I also tried using the window.addEventListener function, but the popup appears on all pages of my website. I would like to display this confirmation message only on the page of this specific Vue component.

Here are some examples:

This code is inside the Vue Component:

beforeRouteLeave (to, from, next) {
  const answer = window.confirm('Confirmation Message')
  if (answer) {
    next()
  } else {
    next(false)
  }
},

This code is inside the Vue Component, but outside the export default:

window.addEventListener('beforeunload', (event) => {
  if (logic) {
    event.returnValue = 'Are you sure you want to leave? Unsaved changes will be lost.'
  }
})

How can this be achieved?

Answer №1

If you're thinking about leaving...

const confirmLeave = () => window.confirm('Are you sure you want to leave? Unsaved changes will be lost.')

window.addEventListener('beforeunload', evt => {
  if (!confirmLeave()) {
    evt.preventDefault();
    evt.returnValue = true;
  }
});

When using the beforeRouteLeave method, consider using if (confirmLeave()) instead of if (answer).

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

Customizing Geonames JSON Ajax Request

Having found the code I needed from a sample website, I am now seeking help to customize it to only display results from the USA. This is the current code snippet: $(function() { function log( message ) { $( "<div>" ).text( message ).pr ...

The javascript file does not load and stringByEvaluatingJavaScriptFromString is also not running?

In my application, I am downloading an HTML file from the server and displaying it in a uiwebview. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths firstObject]; NSStri ...

Unable to update React state on a component that is unmounted while utilizing Redux

Utilizing Redux for managing a global Dialog component, I am passing the child components to the Dialog component through Redux actions. You can find a functional example in this codesandbox: https://codesandbox.io/s/suspicious-keldysh-uuolb?file=/src/App ...

Removing HTML elements with jQuery's .html() method

I have a scenario where I am storing the complete content of a <tbody> in a variable, and after some table manipulation, I need to revert back to the original content of the <tbody>. However, when I try to switch back to the original content, j ...

Displaying information in ejs format

I am currently working on a project to develop a basic webpage that requires the user to input a specific time and then click on submit. Once submitted, I want the relevant data linked to that input to be displayed on the webpage. Upon clicking the submit ...

Remove duplicate entries and store them in an array while also applying an extra condition in JavaScript

I'm looking to filter a list of objects based on different city and state values, then create a new list of cities from the filtered objects where the temperature is less than 40. The condition is that both the state and city should not be the same. l ...

Discovering the method to incorporate a data-icon attribute within select options using vue.js

UPDATE before modification dataIcon: " @/images/flag-ukraine.svg" after modification dataIcon: require("@/assets/svg/flag-ukraine.svg"), notable change with require() I am using Materialize CSS select. When I use a URL for dataIcon ...

Are there any alternatives to jQuery address in the realm of dojo?

Currently, I am working on developing an ajax application using dojo. I am curious if there is a feature comparable to jQuery Address in terms of functionality. My goal is to implement ajax-based hash url navigation similar to Twitter and Facebook using do ...

Combining Quasar, Express, and Electron for a seamless app production fails to initiate the Express server

I am currently in the process of developing an app, and everything seems to be functioning correctly while I am in developer mode. The issue arises when I package the app, as it opens but fails to start the express server. During development testing, I ty ...

Discover the method for retrieving the upcoming song's duration with jplayer

Hey there, I have a question regarding the jPlayer music player. Currently, I am able to retrieve the duration of the current song using the following code snippet: $("#jquery_jplayer_1").data("jPlayer").status.duration; However, I now want to obtain t ...

Unable to retrieve the properties of a JavaScript object

Currently I am working on a React webApp project and encountering difficulties when trying to access data within a JavaScript Object. Below is the code snippet in question: const user_position = System.prototype.getUserPosition(); console.log({user ...

Troubleshooting issue with Bootstrap slider: CSS display problem

After downloading the Bootstrap slider from this link: https://github.com/seiyria/bootstrap-slider, I navigated to \bootstrap-slider-master\dist and transferred the bootstrap-slider.js and bootstrap-slider.min.js files to my js folder. Additional ...

Exploring the proper method for closing connections in Node JS and the pg module

I'm experiencing frustration with the node pg module as I keep encountering a 'too many clients already' error. For instance, in my app.js file, I handle various routes where I query data from postgres. Here's a snippet of how app.js i ...

What is the best way to conceal a row when a particular field is devoid of content?

Is it possible to hide an entire table row if a field is empty? For example: https://i.sstatic.net/tMW7L.png If a certain field is empty, I want the entire row to be hidden, either using JavaScript or jQuery. I have tried some methods but none of them fu ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...

What is the best way to display text from one text field onto another text field?

Here's a challenging question that I've been pondering... Issue: I am using a virtual keyboard that needs to interact with different text fields on various pages. Every time I click on a text field, the keyboard should appear, and every key I pr ...

Exploring the power of Knockout Js and Typeahead libraries

https://i.stack.imgur.com/38iZc.png Hello experts in Knockout and typeahead, I am receiving suggestions from the typeahead js as shown above. I have my data supplied in an array format var itemsRandom= ['Apple', 'Ball','Ape&apos ...

Adjust the width of a div within a nested iframe using jQuery without the need for an identifying ID on the iframe itself

Below is the code sample I'm working with: <iframe> <div id="inner_div"> Here's some text! </div> </iframe> I am aware that by adding an id to the iframe, I could follow the instructions provided here to access t ...

When I try to insert new data into a MongoDB collection during an update operation, the existing data is being overwritten instead

While updating data, I have a requirement to also add new data. Specifically, I need to append data to an existing object in a for loop that stores data in a database. However, when attempting this, the data is being updated instead of added to the current ...

Tips on transmitting checkbox data from AJAX to PHP

I'm currently working with this code and facing an issue where data from checkboxes is being sent to PHP one by one. I want to be able to send multiple selected data at once. How can I modify the code to achieve this? $('#lunas').click(funct ...