Is there any difference between running js script of quickadd and running in obsidian console

Things I have tried

Hi, I try to create a QuickAdd macro which will run a js script.

In the js script, I want to create a canvas file and move it to the specific directory rather than the default one.

The js script code is as following:

// step1. create the canvas file with execute the command
await app.commands.executeCommandById('canvas:new-file');

// step2. get the created file info
// ERROR: `console.log( app.workspace.activeLeaf.view.file)` print the file as null
let canvasFilePath =  app.workspace.activeLeaf.view.file.path;

// step3. rename the file for moving it to the target directory
let tFile = app.vault.getAbstractFileByPath(canvasFilePath);
app.vault.adapter.rename(tFile, targetDir);

What I’m trying to do

As the comment shows in the code before, when I run the js script with QuickAdd command, the workspace.activeLeaf.view.file is undefined.

But when I tried it in obsidian console, it seems ok. I don’t know why or what did I missing.

In the last image you do the app.workspace.activeLeaf.view.file twice, and the first time it does return undefined. Then you execute the canvas:new-file command and it returns true, and then you get the activeLeaf file.

My point being, that the app.workspace.activeLeaf.view.file is most likely context sensitive, and in the first case it was not within a context having that, and in the second it was. In your code, you should most likely check for the return value of the command execution and most likely you should also check whether the activeLeaf file is actually set before trying to handle it.

As to what to do if the command execution returns false, I’m not sure. But it is robust programming to actually test that the value you’re going to use do have legal values before using them.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.