解决vscode扩展插件开发webview中的请求跨域问题

在webview中是无法发送跨域请求的,可以通过消息机制,在插件中发请求,然后将请求结果传递给webview

我的代码是基于vscode-webview-ui-toolkit-samples-vue来写的

webview vue组件中的代码示例

javascript 复制代码
async function initData() {
  // 向插件发送消息
  vscode.postMessage({
    command: 'getData',
    text: 'demo'
  })
}

// 监听插件消息
window.addEventListener('message', event => {
  const message = event.data; // The JSON data our extension sent

  switch (message.command) {
    case 'resultData':
      // 接收到数据
      const data = message.data
      // 然后就可以在webview中使用数据了
      break;
  }
})

onBeforeMount(() => {
  initData()
})

插件panel中的代码示例

javascript 复制代码
/**
   * Sets up an event listener to listen for messages passed from the webview context and
   * executes code based on the message that is recieved.
   *
   * @param webview A reference to the extension webview
   * @param context A reference to the extension context
   */
  private _setWebviewMessageListener(webview: Webview) {
    // 监听webview消息
    webview.onDidReceiveMessage(
      (message: any) => {
        const command = message.command;
        const text = message.text;

        switch (command) {
          case "getData":
            axios.get(`http://x.x.x.x:10200/${text}/list`).then(res => {
              // 将接口返回的数据发送给webview
              // 注意用axios发请求的化,发送数据中的data需要取res.data,而不能直接用res
              // 否则会报"TypeError: Converting circular structure to JSON"错误
              webview.postMessage({command: 'resultData', data: res.data});
            });
            return;
          // Add more switch case statements here as more webview message commands
          // are created within the webview context (i.e. inside media/main.js)
        }
      },
      undefined,
      this._disposables
    );
  }
相关推荐
一帘忧梦4 小时前
vscode 搭建stm32开发环境 +HAL 库
ide·vscode·编辑器
剑神一笑6 小时前
CSS Animation Timeline 可视化动画编辑器:从关键帧到流畅动画
前端·css·编辑器
独隅1 天前
Visual Studio 2026 详细安装教程和配置指南
ide·visual studio
He少年1 天前
【AI 辅助案例分享】
人工智能·c#·编辑器·ai编程
Robot_Nav1 天前
AI 编程助手 Skill 完全指南:VS Code · Trae CN · Claude Code
人工智能·vscode·skill·trae·claude code
vortex51 天前
Kali Linux 安装与使用 Code-OSS / VSCodium :VSCode 轻量替代
linux·运维·编辑器
lifewange1 天前
Pycharm和IDEA中安装Cursor的方法
ide·pycharm·intellij-idea
生而为虫1 天前
在VScode中使用Claude Code agent并配置模型(仅mac电脑实际操作,windows电脑未实际操作如有问题可留言)
windows·vscode·macos
skilllite作者1 天前
Zed 1.0 编辑器深度评测与实战指南
开发语言·人工智能·windows·python·编辑器·agi
读书札记20222 天前
visual studio 调试技巧总结
ide·visual studio