I am looking to send data to an API whenever the user closes the browser tab

Hey guys, I need some help with a problem I'm facing in my current scenario. I am working on a feature to lock bookings for other admins, and I have created a field in the bookings table to store the admin's ID when they access the booking. However, if the user closes the tab, the booking remains locked for other admins as well.

I've tried various methods in vueJs like using the beforeunload method, Xhr requests, and axios calls, but none have been successful in resolving this issue. Can anyone suggest what else I can do to fix this problem?

removeUser () {

    var params = JSON.stringify({ locked_by: '' });
    let xhr = new XMLHttpRequest()
    xhr.open('PUT',Url, true)
    xhr.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem('app_access_token'))
    xhr.setRequestHeader("Content-length", params.length);
    xhr.setRequestHeader("Content-type", "application/json; charset=utf-8")
    xhr.responseType = 'arraybuffer'
    xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
}
xhr.send(params);
mounted() {
    window.addEventListener('beforeunload', this.removeUser)

I also attempted an axios call on the beforeunload event:

removeUser (id) {
    let payload = {
        locked_by: '',
        id: id
    }
    this.updateIsLockedField(payload).then(() => {
        console.log('updated')
        return 'something'
    })
},

If you have any suggestions or advice on how to trigger an API call when the user closes the tab, it would be greatly appreciated!

Answer №1

When it comes to executing actions on tab/window close, there isn't a foolproof method. The concept of "closing" a tab essentially means releasing resources, making it challenging to perform tasks at that moment.

In this scenario, one approach could be to have the frontend maintain a component that automatically expires when the tab is closed.

You could establish a websocket connection for various functions, monitoring its status. If the connection terminates and does not reconnect within a short timeframe, you can infer that the client has disconnected. Alternatively, you can periodically send pings while the tab remains open. If consecutive pings are missed, it indicates a disconnection from the client's end.

Answer №2

To achieve a synchronous request, pass 'false' to the open method like this: xhr.open('PUT', Url, false)

removeUser () {
    var params = JSON.stringify({ locked_by: '' });
    let xhr = new XMLHttpRequest()
    xhr.open('PUT', Url, false) // Setting it to `false` for synchronous request
    xhr.setRequestHeader("Authorization", 'Bearer ' + localStorage.getItem('app_access_token'))
    xhr.setRequestHeader("Content-length", params.length);
    xhr.setRequestHeader("Content-type", "application/json; charset=utf-8")
    xhr.responseType = 'arraybuffer'
    xhr.onreadystatechange = function() {// Call a function when the state changes.
    if(xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
}

Answer №3

In Vuejs, you have access to various hooks, one of which is the destroyed hook. This hook is triggered when the vue instance is closed, such as when the browser is closed. Here's an example:

destroyed() {
    callYourFunctionName
}

I am currently working on a similar system where we need to unlock data when a user leaves. After extensive research, it seems that there is no guaranteed way to ensure that your function will complete its logic before the browser closes. If your function requires some time to execute, it may not work as expected.

In our case, we first attempt to handle this in the destroyed() hook and have a backup security measure in place that unlocks any registers after 10 minutes of user inactivity.

I hope this information proves helpful to you.

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

Updating data on a page in Vue to show the latest information

I am currently working on a vue project where I need to display a list of users and their details. When I click on the edit button for a particular user, I want to be able to update that user's information and have it reflect in the list immediately. ...

Leverage the Ajax response within a Jade template

I'm currently utilizing ExpressJS with the Jade template engine. My goal is to achieve the following: Within a Jade file, I need to extract a variable that will be used in a JavaScript file. This JavaScript file will then make an Ajax request to the ...

What is the best way to show a message on a webpage after a user inputs a value into a textbox using

I have a JSFiddle with some code. There is a textbox in a table and I want to check if the user inserts 3000, then display a message saying "Yes, you are correct." Here is my jQuery code: $("#text10").keyup(function(){ $("#text10").blur(); ...

Increase the current time by 50 minutes

I have a dropdown menu with various time options like this: <select name="" id="delyvery-hour"> <option value="18:00">18:00</option> <option value="18:05">18:05</option> <option ...

Exploring the integration of SQLite in a PhoneGap mobile application

I've been working on a phonegap app and trying to implement sqlite functionality. Despite following a tutorial, it's not functioning properly. Take a look at my code: <script type="text/javascript"> //add listener when device ready docume ...

Jasmine secretly observes the behavior of Angular services

I'm currently in the process of setting up unit tests for an angular controller using jasmine and karma. Due to the length of my code, I won't be able to include it all here. However, I'll provide some snippets: CompilerController.js (the c ...

Error encountered: MongoDB failed to execute Javascript as it was unable to save a DBQuery object in the specified location within the collection.js file

When attempting to modify an existing document in a MongoDb collection, an exception is generated with the following message: javascript execution failed : can't save a DBQuery object at src/mongo/shell/collection.js The following actions are perform ...

Implementing universal styles to injected HTML (v-html)

I am facing an issue while injecting HTML content from my database using Vue. The problem is that although I can successfully inject the HTML, the framework stylesheet (Vuetify) does not seem to be applied to the injected content. The rest of the page ha ...

Having trouble retrieving the table value from an HTML document?

I am trying to retrieve specific information from this source: https://i.sstatic.net/g1wDj.png This information is crucial for fetching data from a database using a primary key. However, extracting this value has proven to be quite challenging. Upon docu ...

Transferring an array from PHP to JavaScript within a function

Having trouble accessing the array returned by a PHP function in JavaScript. Instead of seeing the actual array, I get the message: function Array() { [native code] } How can I retrieve and work with the items in the array? When I try using alert(pad ...

Using the md-date-picker along with the md-menu component

Whenever I try to click on the md-date-picker inside md-menu, it unexpectedly closes. You can view the issue on this CodePen link. This seems to be a bug related to ng-material as discussed in this GitHub issue. Any suggestions for a workaround? Here is t ...

I'm curious if it's possible to modularize a Page Element in Next.js that receives staticProps through a parsedUrlQuery

The scenario involves opening http://localhost:3000/users/101 Desired layout for the page and integration of the second code snippet in [id].tsx import CTASection from '../../components/samples/CTASection'; import { User } from "../../inte ...

Laravel Forbidden: Access Denied

I encountered an error in my code. To troubleshoot, I am currently inserting a static value in the controller to test if it is functioning properly. Below is the code snippet: protected function methodNotAllowed(array $others) { th ...

Converting an Angular1 App into a VueJs app: A step-by-step guide

Let's dive right in: I'm embarking on the journey of revamping an app that originally utilized Angular 1, but this time around I'll be harnessing the power of VueJS 2. As someone unfamiliar with Angular 1, I'm faced with some perplexing ...

Remove repeated selections in a dropdown menu using Vue JS

Could someone offer me some assistance, please? I have 3 dropdown menus that need to display specific subjects based on previous selections. One issue I'm facing is how to remove the initial selection in menu one from both menu two and menu three? I ...

Transfer the text entered in one textbox to another textbox located within a dynamic table

Is there a way to automatically copy the input from a textbox into another textbox within a dynamic table using JavaScript? I need the value entered in the first textbox to be replicated in the textbox inside the dynamic table. Any guidance or assistance o ...

Get rid of the folder from the URL using an <a> tag

I have both an English and French version of my website located at: *website.com/fr/index.php *website.com/index.php Currently, I have a direct link to switch between the two versions: -website.com/fr/index.php -website.com/index.php. However, I ...

PHP Troubleshooting: Resolving Ajax Problems in Symfony 4

I am currently learning Symfony and attempting to integrate Ajax with Symfony. I have placed the Ajax code within a javascript block in Twig and added a simple function in the controller file to test its functionality. However, it seems that the Ajax is no ...

Issue an alert and refresh the webpage when a file extension upload script is detected

Here is the JavaScript code I'm using to restrict the file type extension during uploads: function TestFileType( fileName, fileTypes ) { if (!fileName) return; dots = fileName.split(".") //get the part AFTER the LAST period. fileType = "." + dots[do ...

Error encountered in Node.js: Attempting to modify headers after they have already been sent to the client

When attempting to create a login function and sending post requests using Postman, everything works fine with the correct email and password. However, if I try to send the wrong password, I encounter an error message stating that either the email or passw ...