User Scripts as first-class API concept

Use case or problem

Multiple plugins have introduced the idea of user scripts, JavaScript functions or classes that are loaded from files in your vault and then executed by plugins. Every plugin seems to load, call, and list these scripts slightly differently. Script execution can be brittle depending on implementation and platform.

Proposed solution

I propose that a user script API be added to Obsidian for use by plugin developers to list, load, and invoke user scripts. Additionally, documentation should be added to help users write scripts that work properly.

If we imagine some UserScript API, we’d likely want:

  • list(): Lists all known user scripts by name and path, and potentially by arity.
  • invoke(name, arguments): Invokes a user script with the given arguments.

Ideally, loading and reloading user scripts is done automatically whenever js files are added to the vault, perhaps in some pre-specified location.

As an optional enhancement, a thing I did in Longform was allow user scripts to export a js object with some metadata in addition to a function property, e.g.

module.exports = {
    title: "My script title",
    description: "Some longer description of what I do",
    execute: function() { ... }
}

I can then load all the scripts and display some extra data about them to help the user figure out what they do, and to encourage sharing scripts. It would be neat if Obsidian supported both function and object script exports for this purpose.

Current workaround (optional)

The CustomJS plugin seems closest to “standardizing” user scripts, but requires classes as namespaces, loads scripts alphabetically rather than by dependency resolution, and does not provide API for other plugins to reload or list scripts.

6 Likes

I would love to see this happen, especially to help improve cross platform script management and to allow reusing scripts across plugins more easily.

Allowing script definitions as code blocks in files would be pretty stellar too, but any official user script management would be amazing.