Tauri 中嵌入百度网页:从 iframe 到 Webview 的迁移实践
问题背景
在开发 Tauri 桌面应用时,我们曾需要在插件窗口中嵌入百度首页。最初方案是在 src/plugins/baidu/index.vue 中使用 iframe,但很快遇到了点击无响应的问题。经过排查,最终通过迁移到 Tauri 的 Webview API 成功解决了这一痛点。
我们的技术栈是 Tauri 2.0 + Vue 3 + TypeScript,需求是在保留窗口控制按钮(最小化、最大化、关闭)的同时,加载外部页面。
初次尝试:iframe 的局限
实现代码
<template>
<main data-tauri-drag-region>
<ActionBar
:shrink="false"
:max-w="true"
:icon-color="'black'"
:top-win-label="WebviewWindow.getCurrent().label"
:current-label="WebviewWindow.getCurrent().label"
/>
<iframe src="https://www.baidu.com" frameborder="0"></iframe>
</main>
</template>
<script setup lang="ts">
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
</script>
遇到的问题
上线后用户反馈:打开百度网页之后点击没反应。
原因分析
这并非代码逻辑错误,而是浏览器安全策略的限制:
- X-Frame-Options 限制:百度在响应头中设置了
X-Frame-Options: SAMEORIGIN,明确禁止在 iframe 中嵌入。 - 跨域安全策略:现代浏览器出于安全考虑,会阻止 iframe 内的点击事件和脚本执行。
- 交互体验差:即使能加载,iframe 内的交互也会受到各种限制,无法获得原生体验。
iframe 方案在嵌入第三方网站(尤其是大型网站如百度)时存在根本性限制,必须寻找替代方案。
解决方案:使用 Tauri Webview API
为了找到正确的实现方式,我研究了项目中其他使用外部链接的插件,发现 src/components/rightBox/chatBox/Bot.vue 中的 Webview 实现非常关键。
Webview API 的优势
相比 iframe,Tauri Webview API 具有以下显著优势:
- 无跨域限制:使用系统级 webview 组件,不受浏览器同源策略限制。
- 完整交互支持:支持所有正常的网页交互(点击、输入、导航等)。
- 更好的性能:原生组件,渲染性能优于 iframe。
- 灵活的窗口管理:可以精确控制位置、大小、焦点等。
实现迁移
替换模板结构
首先将 iframe 替换为一个容器 div,用于挂载 Webview 实例:
<template>
<main data-tauri-drag-region>
<ActionBar
:shrink="false"
:max-w="true"
:icon-color="'black'"
:top-win-label="currentWindow.label"
:current-label="currentWindow.label"
/>
<div data-tauri-drag-region>
<div ref="webviewContainer"></div>
</div>
</main>
</template>
编写 Webview 创建逻辑
接下来处理核心的 Webview 初始化与生命周期管理。这里需要特别注意窗口实例的获取方式以及资源清理。

