解决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
    );
  }
相关推荐
ai-ai3606 小时前
vscode里几种程序调试配置
ide·vscode·编辑器
斯普润布特7 小时前
Idea 配合 devtools 依赖 实现热部署
ide·intellij-idea·devtools
PyAIGCMaster8 小时前
vscode git push 记录
ide·git·vscode
黛琳ghz8 小时前
CodeBuddy(腾讯云代码助手)最新功能——智能体 Craft 体验
人工智能·vscode·ai·腾讯云·codebuddy·腾讯云代码助手·craft
小智学长 | 嵌入式10 小时前
SOC-ESP32S3部分:2-2-VSCode进行编译&烧录
ide·vscode·编辑器
EstrangedZ10 小时前
使用vscode MSVC CMake进行C++开发和Debug
c++·ide·vscode·msvc·cmake·visual studio
xuanjiong14 小时前
苍穹外卖day1实战,Idea中Lombok编译时“找不到符号”,更改JDK版本最全流程,作者亲身尝试
java·ide·intellij-idea
在路上@Amos17 小时前
虚拟环境中VSCode运行jupyter文件
ide·vscode·jupyter
KerwinChou_CN17 小时前
自由开发者计划 001:创建一个用于查看 Jupyter Notebook 的谷歌浏览器插件 Jupyter Peek
ide·python·jupyter·plotly·scikit-learn
Zhen (Evan) Wang17 小时前
Visual Studio 2022 无法编译.NET 9 项目的原因和解决方法
ide·.net·visual studio