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.

10 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?

add this code after first line, to exclude folder you want

	if(file.path.startsWith('TemplateFolder')){
		return
	}

Beware:
I have been using this script, and I am fairly sure it has corrupted every image attachment i opened in obsidian

I am not familiar with Java script, but I am fairly confident that adding the following if statement after the first line should prevent this issue:

	if(!file.path.endsWith('.md')){ 
		return 
	}
1 Like

It seems like if you put this script in a template, it will work for new notes that you create. But what about tracking all the notes you have already created? Is there a way to do this without adding it to each note manually?

In 2023 February, MetaEdit breaks Obsidian - at least it broke mine, and then I lost 2 precious hours with resetting and reconfiguring everything the way it used to be.

MetaEdit doesn’t support the new Obsidian version, it was 7 months ago the plugin was updated the last time.