当前位置: 首页 > article >正文

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

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

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

webview vue组件中的代码示例

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中的代码示例

/**
   * 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
    );
  }

http://www.kler.cn/a/531036.html

相关文章:

  • EtherCAT主站IGH-- 49 -- 搭建xenomai系统及自己的IGH主站
  • 使用 PyTorch 实现逻辑回归并评估模型性能
  • Java的Integer缓存池
  • 【数据结构】_复杂度
  • 【算法设计与分析】实验8:分支限界—TSP问题
  • 【深度学习】DeepSeek模型介绍与部署
  • 【前端】ES6模块化
  • 大模型综合性能考题汇总
  • 【PyQt】keyPressEvent键盘按压事件无响应
  • 单行函数与聚合函数
  • Windows 安装Linux子系统
  • Autosar CP RTE规范解读之RTE与VFB以及RTE API关系解析
  • 【机器学习篇】K-Means 算法详解:从理论到实践的全面解析
  • 高阶开发基础——快速入门C++并发编程3
  • 掌握 HTML5 多媒体标签:如何在所有浏览器中顺利嵌入视频与音频
  • va_list va_start va_end的概念和使用案例
  • python:如何播放 .spx 声音文件
  • Mac电脑上最新的好用邮件软件比较
  • Docker环境下Nacos的保姆级安装教程
  • UE PlayerState
  • 【FreeRTOS 教程 八】直达任务通知
  • YOLOV11-1:YoloV11-安装和CLI方式训练模型
  • 使用Express.js和SQLite3构建简单TODO应用的后端API
  • cf div3 998 E(并查集)
  • 几种用户鉴权的方式对比
  • Kamailio、MySQL、Redis、Gin后端、Vue.js前端等基于容器化部署