How to update metadata using javascript?

I’ve made myself a metabind button that runs a js file for one function, however I also want to be able to update the yaml metadata when I click said button. I essentially want to tick a checkbox property by clicking the metabind button.

A secondary question is, are we able to combine two different functions into one metabind button? Because I’ve made two buttons that each fulfil one task, but I want to complete both tasks by clicking just one button. Is this possible?

Thank you in advance!!

1 Like
app.fileManager.processFrontMatter(file, frontmatter => {

    // Update or add as many fields as you want
    frontmatter['Some property'] = 'Some value'
    frontmatter['Another property'] = 'Some other value'

    // You can even remove properties if you want
    delete frontmatter['Unwanted property']

  })
2 Likes

Thank you for replying!! I’m assuming this goes into the js file right? Although it doesn’t seem to work for me, so I think I might be doing something wrong. The script as it is right now below:

// this was the initial function: to play music when the button was clicked
// audio url was pulled from the "src" value when the audio was embedded into the file
var audio = new Audio('audio/url.mp3');
audio.play();

// property key is "completed", a checkbox property, it is false by default
// the button should switch it to true
app.fileManager.processFrontMatter(file, frontmatter => {
    frontmatter['completed'] = true;
  })

For curiosity’s sake I also stuck the frontmatter code into the metabind button, but that gave an error, understandably

The file variable needs to contain a reference to a TFile, for example:

app.vault.getAbstractFileByPath('Path/To/Some/Note.md')
1 Like

Oh I see, that makes sense. I’m guessing this doesn’t work if I’ve made the button and script as part of a template? I would have to update the file variable for every file I make?

There is essentially nothing you can’t do from within Obsidian using JavaScript.

If you make the template with Templater you can use it’s “destination file” variable, or if you’ve made the template some other way you can use Obsidian’s getActiveFile function.

That’s great to hear!! If you don’t mind, could you show me how? javascript is incredibly new to me and I’m not the best with it. I haven’t made my template with Templater, I think it was just using Obsidian’s core template plugin, so we might have to go the getActiveFile route.

The metabind button code block is the following:

label: "Lecture finished"
hidden: false
id: "buttonplay"
class: lecturedone
style: default
action:
    type: js
    file: buttonplay.js

And the buttonplay.js script is just this one here !

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