You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VSCode扩展开发:如何获取Hover悬浮提示内容?

获取VSCode悬浮提示(Hover)文本内容的实现方法

核心实现思路

要获取指定位置的Hover悬浮提示文本,可借助VSCode官方API提供的vscode.executeHoverProvider命令,该命令能触发目标位置的Hover请求,并返回对应的悬浮提示信息集合。

具体代码示例

import * as vscode from 'vscode';

async function fetchHoverText() {
    // 获取当前激活的文本编辑器实例
    const activeEditor = vscode.window.activeTextEditor;
    if (!activeEditor) {
        vscode.window.showErrorMessage('未检测到激活的文本编辑器');
        return;
    }

    // 获取光标当前所在位置
    const cursorPos = activeEditor.selection.active;
    // 调用API触发Hover请求并获取结果
    const hoverResults = await vscode.commands.executeCommand<vscode.Hover[]>(
        'vscode.executeHoverProvider',
        activeEditor.document.uri,
        cursorPos
    );

    if (hoverResults && hoverResults.length > 0) {
        // 提取所有Hover内容的文本部分
        const hoverText = hoverResults[0].contents.map(item => {
            return typeof item === 'string' ? item : item.value;
        }).join('\n');
        
        console.log('提取到的Hover文本:', hoverText);
        vscode.window.showInformationMessage(`Hover内容:\n${hoverText}`);
    } else {
        vscode.window.showInformationMessage('当前光标位置无悬浮提示');
    }
}

// 将功能绑定到自定义命令,扩展激活时注册
export function activate(context: vscode.ExtensionContext) {
    const commandDisposable = vscode.commands.registerCommand('your-extension.fetchHoverText', fetchHoverText);
    context.subscriptions.push(commandDisposable);
}

关键细节说明

  • vscode.executeHoverProvider是核心API,需传入目标文档的URI和具体位置参数,返回Hover对象数组
  • Hover的contents属性支持字符串或MarkdownString两种类型,需做兼容处理以提取纯文本
  • 调用前需校验是否存在激活的编辑器与有效光标位置,避免报错

内容的提问来源于stack exchange,提问作者sebanim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 11:26:05