Ways to invoke a controller function from a window listener function

Is there a way to trigger the close function from window.onbeforeunload even when closing the app through 'right click' -> 'close window'? It seems that this.close() is not working in this scenario, possibly due to scope issues.

The listener is meant to handle situations where the app does not close properly, but I still need certain tasks to be performed every time the app is closed.

this.close = function () {
    var _PACKAGES_FOLDER = process.env.TEMP + '/dmv/packages';
    this.rmDir(_PACKAGES_FOLDER, false);
    DataFolder.createFolder('packages');
    win.close();
}

window.onbeforeunload = function(){  
    this.close()
}

Is there any solution to this issue?

Answer №1

Just an update: process.env is a specific variable used in node.js and cannot be utilized on the client side (when it's served to users).

Additionally, for the onbeforeunload function to work properly, you must include a return statement. In this scenario, simply use return null;.

Here's an example:

window.onbeforeunload = function(){  
  this.close();
  return null;
}

Answer №2

JavaScript code:

(function () {
    dmvMainController.$inject = ['DataFolder','$rootScope','$window'];
    function dmvMainController(DataFolder,$rootScope,$window) {
    // Starts maximized by default (set by main.js)
    var maximized = true;
    var fs = require('fs'),
    path = require('path'),
    filePath = path.join(__dirname,'/../','/../config.json');
    this.configFile = JSON.parse(fs.readFileSync(filePath, 'utf8'));


    // Remove packages folder
    this.rmDir = function (dirPath) {
        var fs = require('fs');
        try { var files = fs.readdirSync(dirPath); }
        catch (e) { return; }
        if (files.length > 0)
            for (var i = 0; i < files.length; i++) {
                var filePath = dirPath + '/' + files[i];
                if (fs.statSync(filePath).isFile())
                    fs.unlinkSync(filePath);
                else
                    this.rmDir(filePath, false);
            }
        fs.rmdirSync(dirPath);
    };

    this.close = function () {
        var _PACKAGES_FOLDER = process.env.TEMP + '/dmv/packages';
        this.rmDir(_PACKAGES_FOLDER, false);
        DataFolder.createFolder('packages');
        win.close();
    } 

    $window.onbeforeunload = function(){
    this.close();
  }
}

angular.module('dmv.core.components').
    component('dmvMain', {
        templateUrl: 'app/views/dmvMain.view.html',
        controller: dmvMainController,
    });

})();

HTML:

<md-toolbar class="root-container">
    <div id="dmv-toolbar" class="md-toolbar-tools no-selectable" layout="row">

        <p class="no-selectable" style="font-size: 16px;">DIGITAL MANUFACTURING <strong>VIEWER</strong></p>

        <div class="draggable" flex></div>

         <md-icon class="siemens-logo" md-svg-src="app/assets/siemens_logo.svg" ng-if="$ctrl.configFile.showSiemensLogo === true"></md-icon>
        <span>
            <md-button class="md-icon-button no-outline" aria-label="Minimize" ng-click="$ctrl.minimize()">
                <md-icon class="control s-18" md-svg-src="app/assets/icon_minimize.svg"></md-icon>
            </md-button>

            <md-button class="md-icon-button no-outline" aria-label="Maximize" ng-click="$ctrl.maximize()">
                <md-icon class="control s-18" md-svg-src="app/assets/icon_maximize.svg"></md-icon>
            </md-button>

            <md-button class="md-icon-button no-outline" id="yourcontainer" aria-label="Close" ng-click="$ctrl.close()">
                <md-icon class="control s-18" md-svg-src="app/assets/icon_close.svg"></md-icon>
            </md-button>
        </span>
    </div>
</md-toolbar>

<tabs-container flex layout="column"></tabs-container>

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

AngularJS: Unable to preserve the data

I'm currently working on an issue with saving updated functions using angularJS. I've managed to edit the data and update it on the database side, but the changes aren't reflecting on the frontend side unless I logout and login again. I need ...

Developing a Node.js and Express REST API for generating tailored routes for custom fields

I'm currently using node.js and express framework to build my REST API server. One of the features I want to implement is similar to the Facebook graph API, where I can pass specific fields in my API routes like: /me?fields=address,birthday,email,do ...

What is the best way to deliver hefty files to users? Utilize the node-telegram-bot-api

bot.sendDocument(id, 'test.zip'); I am facing an issue while trying to send a 1.5GB file using the code above. Instead of being delivered to the user, I receive the following error message: (Unhandled rejection Error: ETELEGRAM: 413 Request En ...

conceal elements using the <option> class隐藏

Although it seems like a simple task, I'm struggling to make it work. I created a form where the user can select a month from a list using the tags: <select> <option> When the selection is changed, the class .gone from the day SELECT is ...

Struggling to create a line break within an SVG using the <tspan> element?

I have a pair of text lines that are wrapped in <tspan> tags. <tspan dy="-11.7890625">welcome</tspan> <tspan dy="16.8" x="285.75">text</tspan> I am trying to add a line break between them, but the <br> tag is not worki ...

Display identical text using JavaScript filter

My search filter highlight is currently displaying [object Object] instead of <mark>match values</mark> when replacing the values. This is the code I am using: this.countries.response.filter((val) => { const position = val.value.toLowerCa ...

Alternate routing based on conditions in Angular

I've used the "$urlRouterProvider.otherwise('{route here}')" syntax in angular to create a catch-all route in Angular UI-Router. One thing I'm curious about is whether it's possible to have conditional "otherwise" routing based o ...

Warning: Node 23468 has encountered an unhandled promise rejection, specifically a MongoServerError that states field names cannot begin with '$'. It is advised to use $getField or $setField instead

Encountering issues with node.js and mongoose when attempting to execute a query, leading to the following error. Despite trying various solutions, nothing seems to have resolved the problem thus far. Currently using mongo DB version 5.0.6, node.js v14.17. ...

Coordinating multiple API requests for optimal performance

I have a task where I need to retrieve data from two different API endpoints. Once both sets of data are fetched, I need to compare the information obtained from each source. I am familiar with fetching data from a single API endpoint and using a callback ...

What is the best way to select a specific button to handle the onSubmit event in a React form with multiple buttons

Imagine having the following HTML structure: <div id="container"></div> <p>Output: <span id="output"></span></p> accompanied by this block of JS code: function otherAction(e) { document.getElementById('output& ...

Decoding JSON using JavaScript

I am dealing with a webservice that uses RestEasy to return a JSON object with a List element. When I try to parse the results in a JavaScript loop, everything works fine if there are two or more elements in the List. However, if there is only one element, ...

Exploring the process of iterating through a JSON post response and displaying its contents within image divs

After receiving a JSON post response, I am looking to iterate over the data and display it in image divs. Can anyone provide guidance on how to achieve this using JavaScript? Thank you. Here is the JavaScript code that handles the JSON post response: cor ...

Issue with Node.js: npm is failing to install now

I'm facing an issue while trying to install a module using npm as it keeps returning errors. Even when attempting to install the same module, like in this example: npm install socket.io The following error is shown: npm ERR! TypeError: Cannot call ...

Store Express app session data in Mocha and Supertest for persistent use

I have developed an Express app where JWT is used for authentication, and the token is stored in the session after login. req.session.JWToken = '<token>'; The authentication middleware is as follows: this.use('(^\/admin')& ...

Is it possible to create a translucent glass floating box over HTML elements, similar to the frosted glass effect seen in iOS7?

Creating an overlapping div with a frosted glass effect typically requires using an image background (like ). I am interested in having a floating div (position:fixed) that can apply a frosted glass effect over any content below it, whether it be an image ...

Deactivate the button while you wait for the Google Maps directionService

When utilizing the Google Maps service to plot a route with multiple waypoints and under slow 3G conditions, I need to deactivate an HTML button until the new route is traced. calculateRoad(departure: any, arrival: any) { const request = { origin: ...

Customizing the MUI X Sparkline: Incorporating the percentage symbol at the end of the tooltip data within the MUI Sparklinechart

Presented below is a SparklineChart component imported from MUI X: import * as React from 'react'; import Stack from '@mui/material/Stack'; import Box from '@mui/material/Box'; import { SparkLineChart } from '@mui/x-chart ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Managing Emails with Vue and Firestore

I am facing an issue with updating the 'email' field. Whenever I try to change the email address, it gets updated correctly. However, when I attempt to log in again, the new email address does not work; only the old one seems to be functional. Ho ...

What is the method for configuring the URL of an ajax request to open in a separate window?

I am currently working on an ajax call where I need to open a URL in a new tab or window. Since I'm still learning about ajax, I would greatly appreciate any help and explanation that you can provide. Below is the code snippet: $.ajax({ url: &apo ...