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.
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.
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.
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.
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.
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.
private _subscriptions: vscode.Disposable;
constructor() {
// Listen to closeTextDocument
this._subscriptions = vscode.workspace.onDidCloseTextDocument(
// your code here
);
}
dispose() {
this._subscriptions.dispose();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With