解决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
    );
  }
相关推荐
吐个泡泡v1 小时前
Maven 核心命令详解:compile、exec:java、package 与 IDE Reload 机制深度解析
java·ide·maven·mvn compile
细节处有神明1 小时前
Jupyter 中实现交互式图表:ipywidgets 从入门到部署
ide·python·jupyter
程序员陆通1 小时前
CloudBase AI ToolKit + VSCode Copilot:打造高效智能云端开发新体验
人工智能·vscode·copilot
任磊abc15 小时前
vscode无法检测到typescript环境解决办法
ide·vscode·typescript
hfut028815 小时前
【vscode使用说明】
vscode·编辑器·vim
weixin_3077791317 小时前
VS Code配置MinGW64编译GNU 科学库 (GSL)
开发语言·c++·vscode·算法
ala咪19 小时前
切换VSCODE 中的默认 shell
vscode
不老刘19 小时前
Tiptap(基于 Prosemirror)vs TinyMCE:哪个更适合你的技术栈?
编辑器·tinymce·tiptap·prosemirror
BIBI204920 小时前
自定义 VSCode 标题栏以区分不同版本
ide·vscode·编辑器
:-)21 小时前
idea配置maven国内镜像
java·ide·maven·intellij-idea