How to know how many times a note is viewed

@temberature in this post writes a script to read the value of the metadata field timesViewed whenever the note is opened and increase by one. I’m writing this post just to add more info in case someone needs a better guide on how to use it, and invite more discussion on how to make it better.

You will need to install MetaEdit and Templater plugins.

Step 1: Put this script into a template note

<%*
this.app.workspace.on("file-open", async (file) => {
	const metaedit = this.app.plugins.plugins["metaedit"].api
	const timesViewed = await metaedit.getPropertyValue('timesViewed', file);
	console.log(timesViewed)
	if(!timesViewed) {
		await metaedit.createYamlProperty('timesViewed', 1, file)
	} else {
		await metaedit.update('timesViewed', timesViewed + 1, file)
	}
})
%>

Optional: If you want to not activate the script on certain notes, add this at the top of the script (thanks @The_Tablet)

this.app.workspace.on("file-open", async (file) => {
    if(file.basename === "name1" || file.basename === "name2") {
        return
    }
    // ...do something
})

It’s because the callback for file-open takes a TFile as one of its arguments, meaning you can check the TFile’s basename in the callback

Step 2: Open Templater’s setting, choose that note as a startup template

You are done.

4 Likes

It is indeed what I am looking for!
Thank you for you sharing. And thanks @temberature and @The_Tablet to write this great script.

1 Like

Hi, @Ooker Could you add exclude about path or tags?