Get backlinks of a file

Hi!
I search a way to get “directly” the backlinks of a file. More specifically, the backlinks of an image.

For example, if I use the filepath or TFile of a png, i could get all files using this image.

It seems that only app.metadataCache.resolvedLinks exists, but it add a lot of complexity to just get the backlinks of a file, as I need to iterate through each MD file to find my own file.

As the graph and backlinks pane already display this information, I think it could be possible to find the file using the API ?

(I would like something like findBacklinks(TFile) or findBacklinksByPath(string)

Although it’s not a part of the public API, you can use this.app.metadataCache.getBacklinksForFile(file).

Example:

// A map-like object that maps a source path to an array of backlinks
const allBacklinks = this.app.metadataCache.getBacklinksForFile(file)

for (const sourcePath of allBacklinks.keys()) {
    // (ReferenceCache | FrontmatterLinkCache)[]
    const backlinks = allBacklinks.get(sourcePath)
    for (const backlink of backlinks) {
        if ('position' in backlink) {
            // This is a ReferenceCache
        } else { // or equivalently: if ('key' in backlink)
            // This is a FrontmatterLinkCache
        }
    }
}

However, it seems that the backlink view does not use this method. I’m not sure how it works.
Also, note that this method internally iterates over the cached links, so probably it’s better to be careful not to call it too often.

1 Like

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