解决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
    );
  }
相关推荐
赔罪7 小时前
Python基础-使用list和tuple
windows·vscode·python·pycharm·list
6v6博客10 小时前
如何在 Typecho 中实现 Joe 编辑器标签自动填充
android·编辑器
qq_3384323711 小时前
IntelliJ IDEA远程开发代理远程服务器端口(免费内网穿透)
java·ide·intellij-idea·远程开发
慕斯-ing14 小时前
VSCode设置内容字体大小
经验分享·vscode·编辑器
广药门徒14 小时前
用Python替代OpenMV IDE显示openmv USB 图像
开发语言·ide·python
遗憾皆是温柔15 小时前
JavaFX - 3D 形状
java·开发语言·ide·学习·3d
TangAcrab16 小时前
vscode flutter 项目连接 mumu 浏览器
ide·vscode·flutter
zxb@hny1 天前
vscode命令面板输入 CMake:build不执行提示输入
c++·ide·vscode
Hi Man1 天前
Python之如何在Visual Studio Code 中写的python程序打包成可以在Windows系统下运行的.exe程序
开发语言·vscode·python