Is there a way to activate Toast notification before the window's onbeforeunload event?

Here's a snippet of JavaScript that I have been working on. It currently pops up an alert when someone tries to leave a form without completing it. However, my goal is to display a Toast notification first with some additional information informing the user that all their work will be lost.

The issue I'm facing is that the Toast only appears after the window alert, but I want it to show before. Is there a way to achieve this? The Toast doesn't require any interaction at this point; I simply want it to provide a brief message in the bottom right corner of the screen indicating that the process will reset.

<script>
window.onbeforeunload = () => {
    console.log(window.in_progress);
    const toastLiveExample = document.getElementById('liveToast')
    const toast = new bootstrap.Toast(toastLiveExample)
    toast.show()
    if(window.in_progress > 0){
        console.log(window.in_progress);
        return true;
    };   
};
</script>

Answer №1

I am unable to locate the alert() function in your code. However, it seems like the issue you are experiencing is due to the alert appearing before the toast animation completes. To resolve this, ensure that the alert is triggered after the toast has finished animating. You can achieve this by adding the following snippet to your code (ensure it only executes once as it appends a new event listener to the toast each time it is called):

toast.addEventListener('shown.bs.toast', () => { // This runs after the toast becomes visible to the user
  // Trigger the alert here
  alert("Your alert text");
})

update

It appears there is no way to remain on the page while preventing the default browser pop-up [2], which means the toast cannot fully animate before the pop-up appears.

I also explored the option of creating a custom pop-up after the toast display; however, determining the user's intended destination for navigation upon clicking 'confirm' proved challenging [3].

In light of these constraints, the only solution I can propose is to disable the toast animation entirely by adding the

data-bs-animation="false"
attribute to the toast's HTML [4]. This should allow the toast to be displayed before the pop-up triggers.

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

Having difficulty in sending updated attribute data to MongoDB while trying to edit a User schema in the MERN stack

Currently, the test site functions in the following manner: Upon registration, a user can create an account. However, during the registration process, only the email and password are required inputs, leaving the name attribute empty. The User model is def ...

"IOS exclusive: Encounter INVALID_STATE_ERROR on IOS devices only, not on Android, OSX, or Windows platforms

While developing an HTML5 web page with audio functionality using JavaScript, I encountered an issue. Initially, the basic version of my webpage successfully loaded and played audio files in different formats (e.g., ogg vs mp3) across various OS/browser co ...

After a duration of 4 minutes, an ERR_EMPTY_RESPONSE is thrown in response to the

My angular 5 node app involves sending a request to the server and waiting for a response. There are instances where the response takes around 5-6 minutes to arrive. However, an ERR_EMPTY_RESPONSE error is triggered by the http method after just 4 minutes ...

Best Way to Eliminate "#" Symbol from URL Address in UI-Router

My website URL is structured as follows: This is the index page where I utilize Angular UI-Router to navigate to different views, however, the URL retains the hash symbol (#) like this: Query: I am looking for a way to eliminate/remove the hash tag from ...

Streamline JSON arrays into separate variables based on their respective categories

Received a JSON output from a PHP file with the following structure; [{"device_id":"9700001","sensor_value":"31.5","update_time":"2017-04-28 18:49:06"}, {"device_id":"9700002","sensor_value":"31.5","update_time":"2017-04-28 18:47:05"}, {"device_id":"97000 ...

Difficulties encountered when trying to load liquid using Javascript

Having trouble loading the Shopify liquid object {{product.price | json}} into JS, as it's displaying NaN with the current code on the front end. Any suggestions on how to properly pass liquid into JS? I've tried two functions but neither seem t ...

Updating the textarea with Ajax without the need for a button click or refreshing the

I need to implement a feature where a textarea will automatically update the database without requiring the user to click on any buttons or refresh the page. The idea is that after a keyup event, there should be a 2-second countdown timer. If no additional ...

Determine whether there are three or more identical values when comparing two objects in typescript

Hello there, I am in need of some assistance as I am unsure where to begin. Any help would be greatly appreciated. Here are the two objects I have: const Questions = { five: "c" four: "c" one: "a" three: "a" two ...

Testing JavaScript performance using the V8 engine

function add(x, y) { return x + y; } console.time("clock1"); for (var i = 0; i < 90000000; ++i) { add(1, 2); add('a','b'); } console.timeEnd("clock1"); function combineText(x, y) { return x + y; } fu ...

Is there a way for me to know when ng-options has completed updating the DOM?

I am currently working on integrating the jQuery multiselect plugin using a directive within my application. Here is the select element: <select multiple ng-model="data.partyIds" ng-options="party.id as party.name for party in parties ...

Expanding the content width of Bootstrap Nav Pills

I'm currently working with Bootstrap pills that feature two tabs. I would like to customize the width of the tab content container differently for each tab, but I'm unsure how to achieve this. The tab-content class currently sets the same width f ...

Utilizing the map function on an object that includes several arrays

I have a situation where my props object contains both a user comment array and a userId array. Initially, I only had the user comment array, which allowed me to style each comment individually using the map function. Now that there are two arrays inside m ...

Is it acceptable to use JavaScript files in the pages directory in NEXTJS13, or is it strongly advised to only use TypeScript files in the most recent version?

In the previous iterations of nextJS, there were JavaScript files in the app directory; however, in the most recent version, TypeScript files have taken their place. Is it still possible to begin development using JavaScript? I am working on creating an a ...

NG-model not visible to AngularJS Controller's filter

Finally, the code is working perfectly. It's a mystery to me. I created a custom filter to use with ng-repeat. The code is implemented within a Controller ... .controller('makeOrderController', function ($scope, $timeout, $ionicLoading) { ...

Navigate JSON Object - Prior Action

I am looking for a solution related to the following question/answer: How can I cycle through JSON objects one by one in AngularJS on click I need help with a function that displays the previous item from a JSON object. When the first item is selected, c ...

The MomentJS difference calculation is incorporating an additional hour

I am currently working on a project that involves time calculations. const currentCETTime = moment.tz('2020-03-18 15:58:38', 'Europe/Madrid'); const limitCETTime = moment.tz('2020-03-18 18:00:00', 'Europe/Madrid') ...

Can a gulpfile be written in ES6 syntax?

Question: Is there a way to write my gulp file in ES6 to utilize import instead of require, and use => syntax in place of function()? I have the option to use io.js or any version of node.js. gulpfile.js: import gulp from "./node_modules/gulp/index.j ...

You cannot use a return string in an ajax call with onbeforeunload

Trying to make an ajax call and determine whether to navigate away from a page based on the response. This is what has been attempted so far: window.onbeforeunload = function(e) { $.when($.ajax({ url: checkUrl, async: false, ty ...

Implementing efficient loading and dynamic updates in web applications with Angular.js and php through

Currently, I am working on a project that requires lazy loading of images. However, a new requirement has come up which involves a server batch process pulling images from a database at regular intervals. These images must then be appended to the photos ...

Comparison: JavaScript Cookies vs PHP Cookies

I have been trying to implement the following code: JS: Cookies.set(post_id + '_' + user_ip, post_id + "_" + user_ip, { expires: 1 }); PHP: $cookie_str = $post_id.'_'.get_client_ip(); if (isset($_COOKIE[$cookie_str_]) ){ print_r ...