lifecycleService.ts 2.1 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import { ShutdownReason, ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
7 8 9
import { ILogService } from 'vs/platform/log/common/log';
import { AbstractLifecycleService } from 'vs/platform/lifecycle/common/lifecycleService';
import { localize } from 'vs/nls';
10
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
11 12 13

export class BrowserLifecycleService extends AbstractLifecycleService {

14
	_serviceBrand: undefined;
15 16 17 18 19 20 21 22 23 24

	constructor(
		@ILogService readonly logService: ILogService
	) {
		super(logService);

		this.registerListeners();
	}

	private registerListeners(): void {
25
		window.addEventListener('beforeunload', e => this.onBeforeUnload(e));
26 27
	}

28
	private onBeforeUnload(event: BeforeUnloadEvent): void {
29 30 31
		const logService = this.logService;
		logService.info('[lifecycle] onBeforeUnload triggered');

32
		let veto = false;
33 34 35 36 37 38 39

		// Before Shutdown
		this._onBeforeShutdown.fire({
			veto(value) {
				if (value === true) {
					veto = true;
				} else if (value instanceof Promise && !veto) {
40
					logService.error('[lifecycle] Long running onBeforeShutdown currently not supported in the web');
41
					veto = true;
42 43 44 45 46 47 48
				}
			},
			reason: ShutdownReason.QUIT
		});

		// Veto: signal back to browser by returning a non-falsify return value
		if (veto) {
49 50 51 52
			event.preventDefault();
			event.returnValue = localize('lifecycleVeto', "Changes that you made may not be saved. Please check press 'Cancel' and try again.");

			return;
53 54 55 56 57
		}

		// No Veto: continue with Will Shutdown
		this._onWillShutdown.fire({
			join() {
58
				logService.error('[lifecycle] Long running onWillShutdown currently not supported in the web');
59 60 61 62
			},
			reason: ShutdownReason.QUIT
		});

63 64
		// Finally end with Shutdown event
		this._onShutdown.fire();
65
	}
66
}
67 68

registerSingleton(ILifecycleService, BrowserLifecycleService);