Managing the closure of a Chrome packaged application

Is there a way to execute code before a Chrome packaged app closes?

I have tried the following methods without success:

  • chrome.app.window.current().onClosed
  • chrome.runtime.onSuspend
  • window unload event

For instance:

chrome.runtime.onSuspend.addListener(function() {
    $.ajax({ url: 'http://isup.me/' });    
});

Even though I have implemented this code, no HTTP requests are detected in my web monitoring tool (Fiddler2) after closing the application.

Answer №1

When a packaged app is closing, its Event page (defined in the background scripts section of the manifest) gets notified with a chrome.runtime.onSuspend event. Your code should be handled there. However...

This event indicates that the app is being unloaded and has very little time for cleaning up. As stated:

Once this event is triggered, the app runtime initiates the process of shutting down the app: all events cease to function and JavaScript execution stops. Any asynchronous tasks initiated during this event may not finish processing. Keep the clean-up operations synchronous and straightforward.

$.ajax() is an asynchronous operation that can be slow. Hence, there is a high likelihood of failure when used in a clean-up routine.

In theory, it could be made synchronous, but this feature is disabled in Chrome Apps. Therefore, you cannot reliably make a network request while your app is closing.


There might be a workaround using onClosed handlers:

chrome.app.window.create('window.html', function(win) {
  win.onClosed.addListener(function() {
    // ...
  });
});

This approach could potentially work because any asynchronous tasks started from here technically begin before onSuspend is invoked, preventing the event page from unloading. However, personal testing is necessary to confirm its effectiveness.

Answer №2

Personally, I can confirm that the workaround involving a callback in window.create() which registers a .onClosed listener was extremely effective for me. Interestingly, none of the other documented solutions seemed to work at all during my testing.

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

A guide to updating a particular row and sending parameters with jQuery and AJAX

I am utilizing a JSON response to dynamically display table content. Here is the code I am using to display row values: var rows = ''; for(var i=0; i<response.response.length; i++) { rows += '<tr><td class="country">&ap ...

Having trouble reaching the unidentified function

There are two different scenarios where the 3rd party library (BrowserPrint.js) is used; FUNCTIONAL ENV - JS and jQuery with the 3rd party libraries included simply in the <head> section of the document and the main function being called in $(do ...

Don't give up on the entire task just because one promise was rejected

To handle multiple promises in redux saga, you can use the all function (equivalent to Promise.all): yield all( users.map((user) => call(signUser, user)), ); function* signUser() { yield call(someApi); yield put(someSuccessAction); } An issue ...

What is the best way to toggle DOM classes in React using Material-UI components?

Currently utilizing Material UI alongside React, I have a div element: <div className={classes.div}></div> I am attempting to dynamically add a conditional class to it: <div className={classes.div + divActive ? `${classes.div}__active` : &a ...

Struggling to set the value for a variable within an Angular factory?

When dealing with a variable as an array, I have no trouble pushing objects inside and retrieving the values within the controller. However, when trying to directly assign an object to that variable, I run into issues. If anyone can assist me in achieving ...

Tips for extracting header ID from the HTML/DOM using react and typescript

I developed a unique app that utilizes marked.js to convert markdown files into HTML and then showcases the converted content on a webpage. In the following code snippet, I go through text nodes to extract all raw text values that are displayed and store t ...

Generate a pre-set Promise<T>[] for delivering the component in the absence of a backend at the moment

I need to implement a function that will eventually make a backend call to fetch data. However, at this moment, I just want to return dummy data to the component. How can I create a hardcoded array of Promises with type IMySetting? export function getMyS ...

Sending documents via ExpressJS

I'm currently developing a small application using the latest NodeJS and ExpressJS, but I've encountered an issue with uploading files. My routes are set up like this: app.get('/Share', share.index); app.post('/Share/Process&apos ...

Strategies for identifying specific children in my particular situation

Here's a snippet of my code: <ul id='nav'> <li><h1 id='unique' class='title'>Topic</h1></li> <li><h1 class='toptitle'>Department</h1></ ...

Encountered a syntax issue when attempting to modify state in React.js

I encountered a syntax error when trying to update the state in React.js with the following code. import { FETCH_POSTS } from '../actions/index'; const INITIAL_STATE = { all:[], post: null }; export default (state = INITIAL_STATE, action) => ...

Revisiting the Issue: Jquery Hover Effect Fails to Function in Internet Explorer

Can anyone provide assistance with this issue? The code snippet works perfectly in all browsers except for IE, where the menu does not fade in and looks unattractive. html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.o ...

"Combining background images with javascript can result in displaying visual elements

Hello! I am in need of assistance with a CSS + Javascript fog effect that I have developed. It is functioning properly on Firefox, Opera, and Chrome but encountering issues on IE and Edge browsers. The effect involves moving two background images within a ...

Error: The JSON data contains an unexpected token "p" at the beginning. This error occurred during the

const displayQuote = document.querySelector(".quotes"); fetch(`http://quotes.rest/qod.js?category=inspire`) .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(JSON.stringify(myJson)); }); error message d ...

Using Bootstrap Collapse with EJS Iteration

I am having trouble with this specific section of my ejs file where the collapse feature is not functioning correctly. Can someone please assist me? <% for(var i=0;i<data.length;i++){%> <div id="content"> <p><%=data[i].w ...

"Trouble with React JS redirection feature failing to redirect as intended

Could someone please help me troubleshoot why the redirect function is not working in my code? There are no error messages showing up, but it seems like the Redirect call from the react-router-dom library is causing a problem. The console log displays &apo ...

"VS Code's word wrap feature is beneficial for wrapping long lines of text and code, preventing them from breaking and ensuring they are

text not aligning properly and causing unnecessary line breaks insert image here I attempted to toggle the word wrap feature, installed the Rewrap plugin, and played around with vscode settings ...

Converting an array into an object using Typescript and Angular

I have a service that connects to a backend API and receives data in the form of comma-separated lines of text. These lines represent attributes in a TypeScript class I've defined called TopTalker: export class TopTalker { constructor( pu ...

Is it necessary to sanitize input fields manually in Angular 6?

Is it necessary for me to manually sanitize all user inputs, or does Angular handle this process automatically? In my login form, the data is sent to the server upon submission. Do I need to explicitly sanitize the data, or does Angular take care of sanit ...

Why isn't my JavaScript AJAX PHP if statement functioning properly?

I have been struggling with this issue for more than two hours now and cannot seem to find a logical solution. When I remove the If statement highlighted by --> this arrow, the alert() function works perfectly fine. It triggers when I simply use if(true ...

Using PHP to reset variables for dynamic display in JavaScript

I've been working on retrieving values from a database and storing them in JavaScript variables. While I was successful in accomplishing this task, I encountered an issue when the values in the database are updated - the values of the variables remain ...