我写了一个在VSCode中右击,可以打开内置浏览器的demo。

 

在extension.js中添加执行命令:

let getDoc = vscode.commands.registerCommand('extension.demo.getCurrentFilePath', (uri) => {
        
  const panel 
  = vscode.window.createWebviewPanel( // 创建webview面板
'testWebview', // viewType
    "WebView演示", // 视图标题
    vscode.ViewColumn.One, // 显示在编辑器的哪个部位
    {
        enableScripts: true, // 启用JS,默认禁用
        retainContextWhenHidden: true, // webview被隐藏时保持状态,避免被重置
    }
  );
  panel.webview.html = `<html><body>你好,我是Webview</body></html>` 
        
})
context.subscriptions.push(getDoc);

所有注册类的API执行后都需要将返回结果放到context.subscriptions中

在package.json中添加配置:

"contributes": {
  "commands": [
     {
        "command": "extension.demo.getCurrentFilePath", // 命令
        "title": "打开webview"   // 执行命令的入口
      }
  ],
  "menus": {
    "editor/context": [
       {
          "when": "editorFocus",  // 触发节点
          "command": "extension.demo.getCurrentFilePath",
          "group": "navigation"
       }
    ],
    "explorer/context": [
       {
          "command": "extension.demo.getCurrentFilePath",
          "group": "navigation"
       }
     ]
  }
},