mProjectsCode / obsidian-js-engine-plugin

https://www.moritzjung.dev/obsidian-js-engine-plugin-docs/
GNU General Public License v3.0
73 stars 5 forks source link

Updating a note content on page load #21

Closed abruneau closed 4 days ago

abruneau commented 1 month ago

Hello, I'm trying to update the content of a document with a bunch of Dataview queries. I'm not using DV directly because the links reported by DV wont be visible in the map.

I'm using the following approach:

In my note I have a Meta Bind button triggering a js script. the note also contains two markdown comment

template:

\`\`\`meta-bind-button

style: primary
label: update
action:
  type: js
  file: Scripts/test/account.js

\`\`\`

<!-- private zone -->
<!-- private zone end -->

The core logic of the script is the following:

const noteFile = this.app.workspace.getActiveFile();
let text = await this.app.vault.read(noteFile);
const regex = /<!-- private zone -->([\s\S]*?)<!-- private zone end -->/g;
const newValue = getAccountInfo(noteFile);
const modifiedContent = text.replace(
  regex,
  `<!-- private zone -->\n\n${newValue}\n\n<!-- private zone end -->`
);
await this.app.vault.modify(noteFile, modifiedContent);

It finds the two markdown comments and inserts the content I generated in between.

This is working but I'm looking for a way to automatically run this script when I open the document instead of having to click the button.

Any suggestion?

mProjectsCode commented 1 month ago

A js-engine code block will run every time the note renders, which is when it's opened and when the code block is modified while the note is open. Maybe that does what you need. If not you should look into making this into a plugin. There you can easily use the file open event for this.

abruneau commented 3 weeks ago

I tried to use the code block but when I import the js file which itself import another js file I get an error telling me that engine isn't found

let account = await engine.importJs("Scripts/test/account.js");
account.updateAccountInfo()

ReferenceError: engine is not defined Any idea?

mProjectsCode commented 3 weeks ago

This is a side effect of how I declare the globals since they must be scoped to this execution only and not leak anywhere else. A simple fix is to pass the globals that you need to the function.