Logseq Plugin API
Interact with your local Logseq instance through its JavaScript Plugin API. This skill enables reading, writing, querying, and automating workflows in your Logseq graph.
Prerequisites
Logseq must be running locally with a plugin that exposes the API. The standard way is:
- 1. Install a bridge plugin that exposes
logseq API via HTTP (e.g., via a custom plugin or localhost endpoint) - Alternative: Use Node.js with
@logseq/libs package to script against the running Logseq instance
The API is primarily designed for in-browser plugins, so accessing it from external scripts requires a bridge/proxy.
Core API Namespaces
The Logseq Plugin API is organized into these main proxies:
logseq.App
Application-level operations: getting app info, user configs, current graph, commands, UI state, external links.
Key methods:
- -
getInfo() - Get app version and info - INLINECODE4 - Get user preferences (theme, format, language, etc.)
- INLINECODE5 - Get current graph info (name, path, URL)
- INLINECODE6 - Register custom commands
- INLINECODE7 - Navigate to routes
logseq.Editor
Block and page editing operations: creating, updating, moving, querying content.
Key methods:
- -
getBlock(uuid) - Get block by UUID - INLINECODE10 - Get current page entity
- INLINECODE11 - Get all blocks on current page
- INLINECODE12 - Get all blocks for a specific page
- INLINECODE13 - Insert a new block
- INLINECODE14 - Update block content
- INLINECODE15 - Create a new page
- INLINECODE16 - Delete a page
- INLINECODE17 - Get backlinks to a page
- INLINECODE18 - Add custom slash commands
logseq.DB
Database queries using Datalog.
Key methods:
- -
q(query, ...inputs) - Run Datalog query - INLINECODE21 - Direct Datascript query
logseq.UI
UI operations: messages, dialogs, main UI visibility.
Key methods:
- -
showMsg(content, status) - Show toast notification - INLINECODE24 - Query DOM elements
logseq.Git
Git operations for the current graph.
Key methods:
- -
execCommand(args) - Execute git command
logseq.Assets
Asset management.
Key methods:
- -
listFilesOfCurrentGraph(path) - List files in graph
Common Workflows
Read Content
CODEBLOCK0
Write Content
CODEBLOCK1
Task Management
CODEBLOCK2
Navigation and UI
CODEBLOCK3
Implementation Approaches
Since Logseq's Plugin API is browser-based, you have several options:
Option 1: Bridge Plugin
Create a minimal Logseq plugin that exposes API calls via HTTP:
CODEBLOCK4
Option 2: Node.js Script with @logseq/libs
For automation scripts, use the
@logseq/libs package:
CODEBLOCK5
Note: This requires a running Logseq instance and proper connection setup.
Option 3: Direct Plugin Development
Develop a full Logseq plugin following the plugin samples at:
https://github.com/logseq/logseq-plugin-samples
API Reference
For complete API documentation, see:
- - API Docs: https://logseq.github.io/plugins/
- Plugin Samples: https://github.com/logseq/logseq-plugin-samples
- Type Definitions:
references/api-types.md (extracted from @logseq/libs)
Key Data Structures
BlockEntity
CODEBLOCK6
PageEntity
CODEBLOCK7
Tips & Best Practices
- 1. Always check for null: API methods may return
null if entity doesn't exist - Use UUIDs over IDs: Block UUIDs are stable, entity IDs can change
- Batch operations: Use
insertBatchBlock for multiple inserts - Query efficiently: Datalog queries are powerful but can be slow on large graphs
- Properties are objects: Access with INLINECODE34
- Format matters: Respect user's preferred format (markdown vs org-mode)
- Async all the way: All API calls return Promises
Common Gotchas
- - Page names are lowercase: When querying, use lowercase page names
- Journal pages: Use
journalDay format (YYYYMMDD) not date strings - Block hierarchy: Respect parent/child relationships when inserting
- Format differences: Markdown uses
- for bullets, Org uses INLINECODE37 - Properties syntax: Different between markdown (
prop::) and org (:PROPERTIES:)
Logseq 插件 API
通过其 JavaScript 插件 API 与本地 Logseq 实例进行交互。该技能支持在 Logseq 图谱中执行读取、写入、查询和自动化工作流等操作。
前置条件
Logseq 必须在本地运行,并且需要安装一个暴露 API 的插件。标准方式如下:
- 1. 安装桥接插件:通过 HTTP 暴露 logseq API(例如,通过自定义插件或 localhost 端点)
- 替代方案:使用带有 @logseq/libs 包的 Node.js 脚本与运行中的 Logseq 实例交互
该 API 主要为浏览器内插件设计,因此从外部脚本访问需要桥接/代理。
核心 API 命名空间
Logseq 插件 API 按以下主要代理组织:
logseq.App
应用级操作:获取应用信息、用户配置、当前图谱、命令、UI 状态、外部链接。
主要方法:
- - getInfo() - 获取应用版本和信息
- getUserConfigs() - 获取用户偏好(主题、格式、语言等)
- getCurrentGraph() - 获取当前图谱信息(名称、路径、URL)
- registerCommand(type, opts, action) - 注册自定义命令
- pushState(route, params, query) - 导航到路由
logseq.Editor
块和页面编辑操作:创建、更新、移动、查询内容。
主要方法:
- - getBlock(uuid) - 通过 UUID 获取块
- getCurrentPage() - 获取当前页面实体
- getCurrentPageBlocksTree() - 获取当前页面的所有块
- getPageBlocksTree(page) - 获取指定页面的所有块
- insertBlock(target, content, opts) - 插入新块
- updateBlock(uuid, content) - 更新块内容
- createPage(pageName, properties, opts) - 创建新页面
- deletePage(pageName) - 删除页面
- getPageLinkedReferences(page) - 获取页面的反向链接
- registerSlashCommand(tag, action) - 添加自定义斜杠命令
logseq.DB
使用 Datalog 进行数据库查询。
主要方法:
- - q(query, ...inputs) - 运行 Datalog 查询
- datascriptQuery(query, ...inputs) - 直接运行 Datascript 查询
logseq.UI
UI 操作:消息、对话框、主 UI 可见性。
主要方法:
- - showMsg(content, status) - 显示 Toast 通知
- queryElementById(id) - 查询 DOM 元素
logseq.Git
当前图谱的 Git 操作。
主要方法:
- - execCommand(args) - 执行 git 命令
logseq.Assets
资产管理。
主要方法:
- - listFilesOfCurrentGraph(path) - 列出图谱中的文件
常见工作流
读取内容
javascript
// 获取当前页面
const page = await logseq.Editor.getCurrentPage();
// 获取页面上的所有块
const blocks = await logseq.Editor.getPageBlocksTree(Daily Notes);
// 获取特定块
const block = await logseq.Editor.getBlock(block-uuid-here);
// 使用 Datalog 查询
const results = await logseq.DB.q(
[:find (pull ?b [*])
:where [?b :block/marker TODO]]
);
写入内容
javascript
// 创建新页面
await logseq.Editor.createPage(Project Notes, {
tags: project,
status: active
}, { redirect: false });
// 插入块
const block = await logseq.Editor.insertBlock(
target-block-uuid,
- New task item,
{ before: false, sibling: true }
);
// 更新块
await logseq.Editor.updateBlock(block-uuid, Updated content);
// 批量插入多个块
const blocks = [
{ content: First item },
{ content: Second item, children: [
{ content: Nested item }
]}
];
await logseq.Editor.insertBatchBlock(parent-uuid, blocks, { sibling: false });
任务管理
javascript
// 查找所有 TODO 项
const todos = await logseq.DB.q(
[:find (pull ?b [*])
:where
[?b :block/marker ?marker]
[(contains? #{TODO DOING} ?marker)]]
);
// 将任务标记为 DONE
await logseq.Editor.updateBlock(task-uuid, DONE Task content);
// 获取当前页面的任务
const page = await logseq.Editor.getCurrentPage();
const blocks = await logseq.Editor.getPageBlocksTree(page.name);
const tasks = blocks.filter(b => b.marker === TODO || b.marker === DOING);
导航和 UI
javascript
// 导航到页面
logseq.App.pushState(page, { name: Project Notes });
// 显示通知
logseq.UI.showMsg(✅ Task completed!, success);
// 获取应用配置
const configs = await logseq.App.getUserConfigs();
console.log(Theme:, configs.preferredThemeMode);
console.log(Format:, configs.preferredFormat);
实现方法
由于 Logseq 的插件 API 基于浏览器,你有以下几种选择:
选项 1:桥接插件
创建一个最小的 Logseq 插件,通过 HTTP 暴露 API 调用:
javascript
// 在 Logseq 插件中 (index.js)
logseq.ready(() => {
// 暴露 API 端点
logseq.provideModel({
async handleAPICall({ method, args }) {
return await logseq.Editormethod;
}
});
});
// 然后通过 HTTP POST 从外部脚本调用
选项 2:使用 @logseq/libs 的 Node.js 脚本
对于自动化脚本,使用 @logseq/libs 包:
bash
npm install @logseq/libs
注意: 这需要一个运行中的 Logseq 实例和正确的连接设置。
选项 3:直接插件开发
按照插件示例开发完整的 Logseq 插件:
https://github.com/logseq/logseq-plugin-samples
API 参考
完整的 API 文档请参见:
- - API 文档:https://logseq.github.io/plugins/
- 插件示例:https://github.com/logseq/logseq-plugin-samples
- 类型定义:references/api-types.md(从 @logseq/libs 提取)
关键数据结构
BlockEntity
typescript
{
id: number, // 实体 ID
uuid: string, // 块 UUID
content: string, // 块内容
format: markdown | org,
page: { id: number }, // 父页面
parent: { id: number }, // 父块
left: { id: number }, // 前一个兄弟块
properties: {}, // 块属性
marker?: string, // TODO/DOING/DONE
children?: [] // 子块
}
PageEntity
typescript
{
id: number,
uuid: string,
name: string, // 页面名称(小写)
originalName: string, // 原始大小写
journal?: boolean,
properties: {},
journalDay?: number, // 日记的 YYYYMMDD 格式
}
提示和最佳实践
- 1. 始终检查 null:如果实体不存在,API 方法可能返回 null
- 使用 UUID 而非 ID:块 UUID 是稳定的,实体 ID 可能变化
- 批量操作:使用 insertBatchBlock 进行多次插入
- 高效查询:Datalog 查询功能强大,但在大型图谱上可能较慢
- 属性是对象:使用 block.properties.propertyName 访问
- 格式很重要:尊重用户偏好的格式(markdown 或 org-mode)
- 全程异步:所有 API 调用都返回 Promise
常见陷阱
- - 页面名称是小写:查询时使用小写页面名称
- 日记页面:使用 journalDay 格式(YYYYMMDD)而非日期字符串
- 块层级:插入时注意父/子关系
- 格式差异:Markdown 使用 - 作为项目符号,Org 使用 *
- 属性语法:Markdown(prop::)和 Org(:PROPERTIES:)不同