Writing to the database right before exiting the webpage

A technique for detecting when a user leaves a page.

const captureLeavingPage = () => {
window.onbeforeunload = function (evt) {
    var message = "Are you sure you want to leave?";
    if (typeof evt == 'undefined') {
        evt = window.event;
    }
    if (evt) {
        evt.returnValue = message;
    }
    return message;
}
}

</script>

I am now looking to track when a user clicks "leave this page" and save that action to a database. How can I achieve this?

Answer №1

If you choose not to display the dialog, you can attempt to catch the user as they leave the page. Keep in mind that if you do decide to show the dialog, there are limited options available.

To achieve this, you must make a synchronous request to the server using onbeforeunload.

onbeforeunload = function() {
    var data = 'id=456';
    var xhr = new XMLHttpRequest;
    xhr.open('POST', '/leavingpageevent', false);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", data.length);
    xhr.send(data);
}

It's important to note that this method may not always work reliably. The onbeforeunload event is not standardized, and some browsers might not send the request at all.

In my experience with Chrome, however, I have found this approach to be mostly effective.

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

What is the best way to ensure that the execution of "it" in mocha is paused until the internal promise of "it" is successfully resolved?

const promise = require('promise'); const {Builder, By, Key, until} = require('selenium-webdriver'); const test = require('selenium-webdriver/testing'); const chai = require('chai'); const getUrl = require('./wd ...

Error encountered in THREE.js due to the specific version being imported

At the beginning of my three.js project, I opted for version 0.118.0 and included the necessary imports as shown below. import * as THREE from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf ...

What is the method of updating content on a webpage without altering the page itself or using hashed URLs?

I have a good understanding of how to update webpage content through AJAX and loading remote content. However, I recently came across UStream's innovative new layout. When you click on any video, not only does the content change seamlessly without rel ...

A new update is available for the UpdatePanel and ModalPopup Extender

I have structured my form as follows: <asp:Panel runat="server" Id="xyz"> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <ContentTemplate> 'Gridview featuring edit and delete options ...

What are the consequences of submitting a form to a different website through POST method?

Dealing with a CMS that does not offer an easy way to add a NodeJS route for handling form data can be quite challenging. I'm considering the following setup - would this be considered bad practice or unsafe? Server 1 (Ghost CMS) : www.domain.com &l ...

Serve the JS files in Express separately

I am facing issues with my webapp loading too slowly when using the express.static middleware to serve all my js files. I am considering serving each js file only when needed, such as when serving the html from jade that uses the js file. I have attempted ...

Guide to generating a dynamic manifest.json file for Progressive Web Apps using ReactJS

I am working on a project that requires me to generate a dynamic manifest.json file for my PWA (ReactJS). Below are the relevant code snippets: app.service.js: function fetchAppData() { const requestOptions = { method ...

Tips for managing post-generated buttons using jQuery?

I've created buttons using JavaScript and added them to my HTML. Now I want to use jQuery to handle the clicks on b_1 and b_2. How can I make this work? $("#mainbutton").click(function (){ document.getElementById("content").innerHTML = '< ...

Component not being returned by function following form submission in React

After spending a few weeks diving into React, I decided to create a react app that presents a form. The goal is for the user to input information and generate a madlib sentence upon submission. However, I am facing an issue where the GenerateMadlib compone ...

Combining array outputs from both Promise.all and map functions

Hey, it might seem silly, but it's late and I'm struggling with this issue. My goal is to gather statistics for different types of values and store them in an array. However, the problem lies in the final result: // Data this._types = [{ id: 1, ...

Having trouble initiating NPM in a terminal

I keep encountering an issue whenever I try to start NPM using a command in the terminal. Here is the error message that appears: npm ERR! npm ERR! Did you mean one of these? npm ERR! npm star # Mark your favorite packages npm ERR! npm stars # Vi ...

Automatically scroll the chat box to the bottom

I came across a solution on Stackoverflow, but unfortunately, I am having trouble getting it to work properly. ... <div class="panel-body"> <ul id="mtchat" class="chat"> </ul> </div> ... The issue lies in the JavaScript t ...

Is there a similar feature in jQuery to Prototype's Element.identify?

Are there any built-in jQuery methods or widely accepted default plugins that can automatically assign a unique ID to an element? Or is it necessary to create your own solution for this functionality? I'm seeking the jQuery equivalent of Prototype&apo ...

What is the process of embedding a Vue.js application into an already existing webpage using script tags?

My goal is to integrate a Vue.js application into an existing webpage using script tags. Upon running `npm run build` in my Vue application, I end up with 7 compiled files: app.js app.js.map manifest.js manifest.js.map vendor.js vendor.js.map app.css In ...

Solving Addition and Subtraction Errors in Javascript/Jquery

Upon running the script below, it aims to calculate the height of the browser, as well as the heights of both the header and footer, subtracting them from the initial browser height: var a = $(window).height(); alert (a); var b = $('#header').cs ...

Encountered a JavaScript error when trying to trigger an alert using PHP

I've incorporated fusion maps into one of my applications. In a particular example, I need to transfer values from one map to another chart, However, I encountered an issue where if the data passed is numeric, the alert message displays correctly, b ...

HTML integration of JavaScript not working as expected

My experience with separating files in HTML and JS has been positive - everything works smoothly when I link the JS file to the HTML. However, an issue arises when I decide to include the JS code directly within <script> tags in the HTML itself. The ...

Unable to set $_POST value when using $.ajax post request

I am a beginner in the world of PHP and JavaScript, and I have encountered an issue where I need to make changes to values in an XML document that has been read in. Specifically, I have an HTML Select element that was dynamically generated by PHP code. fu ...

iPython does not show Folium map due to an error message stating: 'Uncaught ReferenceError: L is not defined'

Attempting to showcase a basic map in iPython using the Folium leaflet library. Recently installed iPython via Anaconda with Folium added through Pip. Verified that everything is fully updated Ran this code in iPython import folium map = folium.Map(locat ...

Adjusting a parameter according to the width of the browser window?

Using Masonry, I have implemented code that adjusts the columnWidth to 320 when the screen or browser window width is less than 1035px. When the width exceeds 1035px, the columnWidth should be 240. However, the current code keeps the columnWidth at 320 re ...