Steps to reproduce
Using Note Refactor plugin (but I think it is a general app.workspace problem) when the script used in creating (refactoring) a new note uses app.workspace.lastActiveFile it returns the newly created file, not the parent.
I checked Google search (AI) and got the following explanation: “When you execute a Templater script, app.workspace.lastActiveFile often updates immediately to the newly_created or opened file.”
Expected result
It seems to me the name “lastActiveFile” is meaningless if it doesn’t reliably return the previous file.
Environment
Obsidian iPad app
Moved to help section for not reading/following the BR template.
lastActiveFile isn’t part of the public API, and it tracks the file that is active right now. By the time your script runs, the new note is open, so you get the new note back.
Two ways around it:
-
If you only need the parent’s name or a link to it, Note Refactor has placeholders for that. In the new-note template, {{title}} is the title of the original note and {{link}} is a link to it.
-
In a script, use app.workspace.getLastOpenFiles(). It’s public and returns the paths of the 10 most recently opened files. Skip the new note’s own path and take the first entry left:
const newPath = app.workspace.getActiveFile()?.path;
const parentPath = app.workspace.getLastOpenFiles().find(p => p !== newPath);
const parent = parentPath ? app.vault.getFileByPath(parentPath) : null;
I tested this on Obsidian 1.13.7 desktop: open A, then B, then create and open C. lastActiveFile was C, and getLastOpenFiles() returned ["B.md", "C.md", "A.md"]. The new note sat in second place, so filter it out instead of trusting the order. I haven’t tried it on iPad.