Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when document is closed

I'm working on Visual Studio Code extension and I need to detect when some document window is closed. I know about vscode.workspace.onDidCloseTextDocument event and it works at general.

But if I open a file from the workspace via API:

vscode.workspace.openTextDocument(localPath).then(function (doc) {
    vscode.window.showTextDocument(doc, 1);
});

and then close it, the onDidCloseTextDocument doesn't fire as usual. Its fire but few minutes later.

I know if this is some bug or this is the way VSCode works but I need to know how to detect when document window is closed.

I was reading that opening file via API is some kind of "virtual" file. So, probably this cause the problem.

like image 458
A. Cheshirov Avatar asked Feb 08 '18 19:02

A. Cheshirov


People also ask

How do you know when a tab is closed?

A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.

What is the difference between browser refresh and close?

When we refresh the page (F5, or icon in browser), it will first trigger ONUNLOAD event. When we close the browser (X on right top icon),It will trigger ONUNLOAD event.

How do I know if browser or tab closed in react?

To handle the browser tab close even in React: Use the useEffect hook to add an event listener. Listen for the beforeunload event. The beforeunload event is triggered when the tab is about to be unloaded.

How do you handle browser tab close angular not close refresh?

You can use the onunload event handle to detect this. Checking event. clientY or event. clientX to determine what was clicked to fire the event.


2 Answers

sadly there is no way to catch the document close atm because believe it or not onDidCloseTextDocument fires for more than just closing the file, to test add the below to ur ext active

vscode.workspace.onDidCloseTextDocument((doc) => {
    console.log(doc)
})

and watch the magic in the console.

apart from the totally unrelated documentation

To add an event listener when a visible text document is closed,

use the TextEditor events in the window namespace.

there is no close event on the window namespace https://code.visualstudio.com/api/references/vscode-api#window maybe am blind but if anyone found it plz add it here.

also the isClosed prop on the document is not reliable, because its actually true when you open a document.

like image 153
ctf0 Avatar answered Oct 11 '22 17:10

ctf0


private _subscriptions: vscode.Disposable;

constructor() {

    // Listen to closeTextDocument
    this._subscriptions = vscode.workspace.onDidCloseTextDocument(
        // your code here
    );
}

dispose() {
    this._subscriptions.dispose();
}
like image 32
KYL3R Avatar answered Oct 11 '22 18:10

KYL3R