Giter VIP home page Giter VIP logo

electron-shutdown-handler's Introduction

Electron Shutdown Handler

NPM Typescript N-API License

NodeJS library using native modules to capture the shutdown events on Windows in Electron applications.

Table of Contents

Getting started

Installation

npm install --save @paymoapp/electron-shutdown-handler

Native addon

This project uses NodeJS Native Addons to function, so you can use this library in any NodeJS or Electron project, there won't be any problem with bundling and code signing.

The project uses prebuild to supply prebuilt libraries.

The project uses Node-API version 6, you can check this table to see which node versions are supported.

If there's a compliant prebuilt binary, it will be downloaded during installation, or it will be built. You can also rebuild it anytime by running npm run build:gyp.

The library has native addons for Windows only, but it won't fail during install or during runtime on other platforms.

Example

You can run a demo application by calling npm run demo and use the rmlogotext.exe command to emit the shutdown event without actually shutting the system down.

import ElectronShutdownHandler from '@paymoapp/electron-shutdown-handler';
import { app, BrowserWindow } from 'electron';

app.whenReady().then(() => {
	const win = new BrowserWindow({
		width: 600,
		height: 600
	});

	win.loadFile('index.html');

	ElectronShutdownHandler.setWindowHandle(win.getNativeWindowHandle());
	ElectronShutdownHandler.blockShutdown('Please wait for some data to be saved');

	ElectronShutdownHandler.on('shutdown', () => {
		console.log('Shutting down!');
		ElectronShutdownHandler.releaseShutdown();
		win.webContents.send('shutdown');
		app.quit();
	});
});

Usage

First of all you need to create an electron window, after which you can call the setWindowHandle method. Calling this method is required, otherwise the rest of the functions will throw. This function will store the HWND of the window in the addon and will set that the window will be the first process to shut down (otherwise the renderer process might exit first which results in the crash of electron).

To block the shutdown you need to call the blockShutdown function before a shutdown event occures, but you also need to set up an event listener, otherwise the hook won't be added to the window message callback.

You should also call app.quit() in the shutdown handler.

Please note that this addon is singleton, you can only use it for one window at the moment, so you should always set the main window's handle.

API

Functions

𝑓    setWindowHandle
type setWindowHandle = (handle: Buffer) => void

Set the window handle of the main window. You MUST call this method before calling any other methods.

𝑓    blockShutdown
type blockShutdown = (reason: string) => boolean

Block the system from shutting down. You need to set a reason which will be displayed to the user. The shutdown will only be blocked if you also have a shutdown event listener. The response indicates if the operation was successful.

𝑓    releaseShutdown
type releaseShutdown = () => boolean

Allow the system to shut down. The response indicates if the operation was successful.

Events

The exported object extends the node EventEmitter class.

✨    shutdown

This event is emitted when the system is shutting down. You should avoid calling long running async code here, since as the function finishes, the process will exit.

electron-shutdown-handler's People

Contributors

gergof avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

electron-shutdown-handler's Issues

Cannot find module - production build

Hi. This lib works fine when i test it on development, but if i build for production with electron-builder i get this error on app startup:
"Error: Cannot find module '@paymoapp/electron-shutdown-handler' Require stack: pathToAppData/app.asar/background.js".

It is not installed as dev dependency, so that shouldn't be an issue. Any idea what could be the problem? Thank you

Windows 11 can't stop

ElectronShutdownHandler.on('shutdown', async () => {
      logger.warn('shutdown quit 1')
     await sleep(3000) // = wind reg ProxyEnable
      logger.warn('shutdown quit 2')
      ElectronShutdownHandler.releaseShutdown()
      app.quit()
})

Now it shuts down when the "shutdown quit 2" is not executed

Dependency outdated for VS 2022.

Error logs:

prebuild info begin Prebuild version 11.0.4
prebuild info build Preparing to prebuild @paymoapp/[email protected] for napi 6 on win32-x64 using node-gyp
prebuild info find Python using Python version 3.11.6 found at "C:\Users\xxx\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\python.exe"
prebuild ERR! find VS
prebuild ERR! find VS msvs_version not set from command line or npm config
prebuild ERR! find VS running in VS Command Prompt, installation path is:
prebuild ERR! find VS "C:\Program Files\Microsoft Visual Studio\2022\Community"
prebuild ERR! find VS - will only use this version
prebuild ERR! find VS unknown version "undefined" found at "C:\Program Files\Microsoft Visual Studio\2022\Community"
prebuild ERR! find VS could not find a version of Visual Studio 2017 or newer to use
prebuild ERR! find VS looking for Visual Studio 2015
prebuild ERR! find VS - not found
prebuild ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
prebuild ERR! find VS
prebuild ERR! find VS
**************************************************************
prebuild ERR! find VS You need to install the latest version of Visual Studio
prebuild ERR! find VS including the "Desktop development with C++"
prebuild ERR! find VS For more information consult the documentation at:
prebuild ERR! find VS https://github.com/nodejs/node-gyp#on-windows
prebuild ERR! find VS 
**************************************************************                                                                              
prebuild ERR! find VS
prebuild ERR! configure error
prebuild ERR! stack Error: Could not find any Visual Studio installation to use
prebuild ERR! stack     at VisualStudioFinder.fail (C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\find-visualstudio.js:121:47)
prebuild ERR! stack     at C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\find-visualstudio.js:74:16
prebuild ERR! stack     at VisualStudioFinder.findVisualStudio2013 (C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\find-visualstudio.js:351:14)
prebuild ERR! stack     at C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\find-visualstudio.js:70:14
prebuild ERR! stack     at C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\find-visualstudio.js:372:16
prebuild ERR! stack     at C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\util.js:54:7
prebuild ERR! stack     at C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\util.js:33:16
prebuild ERR! stack     at ChildProcess.exithandler (node:child_process:427:5)
prebuild ERR! stack     at ChildProcess.emit (node:events:514:28)
prebuild ERR! stack     at maybeClose (node:internal/child_process:1091:16)
prebuild ERR! not ok
prebuild ERR! build Error: Could not find any Visual Studio installation to use
prebuild ERR! build     at VisualStudioFinder.fail (C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\find-visualstudio.js:121:47)
prebuild ERR! build     at C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\find-visualstudio.js:74:16
prebuild ERR! build     at VisualStudioFinder.findVisualStudio2013 (C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\find-visualstudio.js:351:14)
prebuild ERR! build     at C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\find-visualstudio.js:70:14
prebuild ERR! build     at C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\find-visualstudio.js:372:16
prebuild ERR! build     at C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\util.js:54:7
prebuild ERR! build     at C:\Users\xxx\Desktop\electron-shutdown-handler\node_modules\prebuild\node_modules\node-gyp\lib\util.js:33:16
prebuild ERR! build     at ChildProcess.exithandler (node:child_process:427:5)
prebuild ERR! build     at ChildProcess.emit (node:events:514:28)
prebuild ERR! build     at maybeClose (node:internal/child_process:1091:16)

Can't build with ia32 support

Hi. Trying to build with arch=ia32 with no luck (Python 3.12, MS VS 2019). Did I miss something? Or could you compile and add to the release electron-shutdown-handler-v1.0.15-napi-v6-win32-ia32.tar.gz by yourself?

Log is the following:

npm run build:gyp

> @paymoapp/[email protected] build:gyp
> node-gyp rebuild --arch=ia32

gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | win32 | x64
gyp info find Python using Python version 3.12.3 found at "C:\Python312\python.exe"

gyp info find VS using VS2019 (16.11.34729.46) found at:
gyp info find VS "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools"
gyp info find VS run with --verbose for detailed information
gyp info spawn C:\Python312\python.exe
gyp info spawn args [
gyp info spawn args 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\gyp\\gyp_main.py',
gyp info spawn args 'binding.gyp',
gyp info spawn args '-f',
gyp info spawn args 'msvs',
gyp info spawn args '-I',
gyp info spawn args 'D:\\temp\\dev\\talk-electron\\node_modules\\@paymoapp\\electron-shutdown-handler\\build\\config.gypi',
gyp info spawn args '-I',
gyp info spawn args 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\addon.gypi',
gyp info spawn args '-I',
gyp info spawn args 'C:\\Users\\y.samoilov\\AppData\\Local\\node-gyp\\Cache\\20.12.2\\include\\node\\common.gypi',
gyp info spawn args '-Dlibrary=shared_library',
gyp info spawn args '-Dvisibility=default',
gyp info spawn args '-Dnode_root_dir=C:\\Users\\y.samoilov\\AppData\\Local\\node-gyp\\Cache\\20.12.2',
gyp info spawn args '-Dnode_gyp_dir=C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp',
gyp info spawn args '-Dnode_lib_file=C:\\\\Users\\\\y.samoilov\\\\AppData\\\\Local\\\\node-gyp\\\\Cache\\\\20.12.2\\\\<(target_arch)\\\\node.lib',
gyp info spawn args '-Dmodule_root_dir=D:\\temp\\dev\\talk-electron\\node_modules\\@paymoapp\\electron-shutdown-handler',
gyp info spawn args '-Dnode_engine=v8',
gyp info spawn args '--depth=.',
gyp info spawn args '--no-parallel',
gyp info spawn args '--generator-output',
gyp info spawn args 'D:\\temp\\dev\\talk-electron\\node_modules\\@paymoapp\\electron-shutdown-handler\\build',
gyp info spawn args '-Goutput_dir=.'
gyp info spawn args ]
gyp info spawn C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\MSBuild.exe
gyp info spawn args [
gyp info spawn args 'build\\binding.sln',
gyp info spawn args '/clp:Verbosity=minimal',
gyp info spawn args '/nologo',
gyp info spawn args '/p:Configuration=Release;Platform=Win32'
gyp info spawn args ]
Выполняется последовательная сборка проектов в этом решении. Чтобы включить параллельную сборку, добавьте параметр "-m".
  nothing.c
  win_delay_load_hook.cc
  nothing.vcxproj -> D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\build\Release\\nothing.lib
  main.cpp
  WinShutdownHandler.cpp
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(26,6): error C2666: Na
pi::CallbackInfo::operator []: для перегрузок (2) есть подобные преобразования [D:\temp\dev\talk-electron\node_modules\@paymoap
p\electron-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\node-addon-api\napi-inl.h(3477,34): message : может быть "const Napi::Value Napi::Callba
ckInfo::operator [](size_t) const" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\build\PaymoWinSh
utdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(26,6): message : или
     "встроенный оператор C++[(napi_callback_info, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-ha
ndler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(26,6): message : при п
опытке сопоставить список аргументов "(const Napi::CallbackInfo, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electr
on-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(31,23): error C2666: N
api::CallbackInfo::operator []: для перегрузок (2) есть подобные преобразования [D:\temp\dev\talk-electron\node_modules\@paymoa
pp\electron-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\node-addon-api\napi-inl.h(3477,34): message : может быть "const Napi::Value Napi::Callba
ckInfo::operator [](size_t) const" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\build\PaymoWinSh
utdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(31,23): message : или
      "встроенный оператор C++[(napi_callback_info, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-h
andler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(31,23): message : при
попытке сопоставить список аргументов "(const Napi::CallbackInfo, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\elect
ron-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(31,48): error C2059: с
интаксическая ошибка: ) [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\build\PaymoWinShutdownHandl
er.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(43,6): error C2666: Na
pi::CallbackInfo::operator []: для перегрузок (2) есть подобные преобразования [D:\temp\dev\talk-electron\node_modules\@paymoap
p\electron-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\node-addon-api\napi-inl.h(3477,34): message : может быть "const Napi::Value Napi::Callba
ckInfo::operator [](size_t) const" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\build\PaymoWinSh
utdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(43,6): message : или
     "встроенный оператор C++[(napi_callback_info, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-ha
ndler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(43,6): message : при п
опытке сопоставить список аргументов "(const Napi::CallbackInfo, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electr
on-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(58,51): error C2666: N
api::CallbackInfo::operator []: для перегрузок (2) есть подобные преобразования [D:\temp\dev\talk-electron\node_modules\@paymoa
pp\electron-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\node-addon-api\napi-inl.h(3477,34): message : может быть "const Napi::Value Napi::Callba
ckInfo::operator [](size_t) const" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\build\PaymoWinSh
utdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(58,51): message : или
      "встроенный оператор C++[(napi_callback_info, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-h
andler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(58,51): message : при
попытке сопоставить список аргументов "(const Napi::CallbackInfo, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\elect
ron-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(58,72): error C2059: с
интаксическая ошибка: ) [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\build\PaymoWinShutdownHandl
er.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(94,6): error C2666: Na
pi::CallbackInfo::operator []: для перегрузок (2) есть подобные преобразования [D:\temp\dev\talk-electron\node_modules\@paymoap
p\electron-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\node-addon-api\napi-inl.h(3477,34): message : может быть "const Napi::Value Napi::Callba
ckInfo::operator [](size_t) const" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\build\PaymoWinSh
utdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(94,6): message : или
     "встроенный оператор C++[(napi_callback_info, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-ha
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(94,6): message : при п
опытке сопоставить список аргументов "(const Napi::CallbackInfo, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electr
on-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(104,36): error C2666:
Napi::CallbackInfo::operator []: для перегрузок (2) есть подобные преобразования [D:\temp\dev\talk-electron\node_modules\@paymo
app\electron-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\node-addon-api\napi-inl.h(3477,34): message : может быть "const Napi::Value Napi::Callba
utdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(104,36): message : или
       "встроенный оператор C++[(napi_callback_info, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-
handler\build\PaymoWinShutdownHandler.vcxproj]
D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\module\WinShutdownHandler.cpp(104,36): message : при
 попытке сопоставить список аргументов "(const Napi::CallbackInfo, int)" [D:\temp\dev\talk-electron\node_modules\@paymoapp\elec
tron-shutdown-handler\build\PaymoWinShutdownHandler.vcxproj]
синтаксическая ошибка: ) [D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler\build\PaymoWinShutdownHand
ler.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\MSBuild.exe` failed with exit code: 1
gyp ERR! stack at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:209:23)
gyp ERR! stack at ChildProcess.emit (node:events:518:28)
gyp ERR! System Windows_NT 10.0.19044
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--arch=ia32"
gyp ERR! cwd D:\temp\dev\talk-electron\node_modules\@paymoapp\electron-shutdown-handler
gyp ERR! node -v v20.12.2
gyp ERR! node-gyp -v v10.0.1
gyp ERR! not

Where is rmlogotext.exe?

I cannot find rmlogotext.exe in the project, neither after running npm run build nor in the release files.

What if I don't have any window?

I have an Electron app that doesn't have any window, only a tray icon.

Unfortunately, tray icons do not have have a getNativeWindowHandle() method to supply to ElectronShutdownHandler.setWindowHandle.

Do you have any ideas on how can I still add the shutdown handler to my app?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.