You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Flutter Web应用嵌入不同服务器的其他Web应用

Flutter Web 嵌入外部网站div的实现方案

一、可行性说明

完全可行,无需iframe即可将部署在webspace A的Flutter Web应用嵌入到webspace B的指定div中,能获得更流畅的集成体验。

二、核心配置与操作步骤

1. 构建Flutter Web时指定资源基础路径

构建时通过参数统一设置所有静态资源的加载路径为webspace A的地址,避免后续手动修改:
执行构建命令:

flutter build web --base-href "https://webspace-a-domain.com/your-flutter-app-path/"

该参数会自动修改构建后index.html内所有资源(main.dart.js、flutter_service_worker.js等)的引用路径,使其直接指向webspace A。

2. 在webspace B的网页中嵌入应用

  • 先给目标div设置唯一ID:
<div id="flutter-app-container"></div>
  • 引入webspace A的Flutter初始化脚本并完成挂载:
<script src="https://webspace-a-domain.com/your-flutter-app-path/flutter.js"></script>
<script>
  window.addEventListener('load', function() {
    _flutter.loader.loadEntrypoint({
      serviceWorker: {
        serviceWorkerVersion: '这里替换为webspace A的index.html中生成的serviceWorkerVersion值',
      },
      onEntrypointLoaded: async function(engineInitializer) {
        const appRunner = await engineInitializer.initializeEngine({
          hostElement: document.getElementById('flutter-app-container')
        });
        await appRunner.runApp();
      }
    });
  });
</script>

注意:serviceWorkerVersion是webspace A构建后index.html里自动生成的字符串,直接复制使用即可。

3. 处理跨域问题

由于资源跨域名加载,需在webspace A的服务器配置CORS响应头,允许webspace B的域名访问资源:

Access-Control-Allow-Origin: https://webspace-b-domain.com

测试环境可临时设置为*允许所有域名访问,但生产环境建议指定具体域名。

三、已构建完成后的补救方案

如果已完成Flutter Web构建,不想重新构建,可手动修改资源路径:

  • 打开webspace A的index.html,将所有相对路径的资源引用改为webspace A的绝对路径,比如把main.dart.js改成https://webspace-a-domain.com/your-flutter-app-path/main.dart.js
  • 同步修改flutter_service_worker.js内的资源缓存路径,确保所有缓存资源指向webspace A。

内容的提问来源于stack exchange,提问作者progNewbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 18:30:54