# Cocos WebView 游戏容器 这是一个 Vite + React 静态 SPA。构建结果只有 `index.html` 和 `static` 资源目录,可以部署到 Nginx、对象存储或任意静态网站托管服务。 ## 开发与构建 ```bash npm install npm run dev npm run build ``` 构建结果: ```text dist/ ├── index.html ├── favicon.svg └── static/ ├── index-[hash].js └── index-[hash].css ``` 也可以用查询参数快速测试游戏地址: ```text http://localhost:3000/?gameUrl=https%3A%2F%2Fgame.example.com%2Fplay ``` ## Cocos 初始化页面 页面加载后会暴露 `window.CocosGameContainer`: ```js window.CocosGameContainer.init({ gameUrl: 'https://game.example.com/play', allowedOrigins: ['https://game.example.com'], bridgeScheme: 'game2c', enableSchemeBridge: true }); ``` 可调用 API: - `setGameUrl(url, allowedOrigins)`:切换 iframe 游戏。 - `openMenu()`:打开菜单弹窗。 - `openGift(payload)`:打开礼包弹窗。 - `closeModal()`:关闭当前弹窗。 - `sendMessageToGame(message, targetOrigin)`:向游戏 iframe 发送消息。 ### Cocos Web 平台调用 浏览器中的 Cocos WebView 是 iframe。跨域时不能通过 `evaluateJS` 直接读取 iframe 内的 `window.CocosGameContainer`,需要由 Cocos 向 WebView iframe 发送命令: ```ts const iframe = this.webView?.nativeWebView as HTMLIFrameElement | null; iframe?.contentWindow?.postMessage( { type: 'game-container:call', method: 'init', args: [{ gameUrl: 'https://game.example.com/play', enableSchemeBridge: false, }], requestId: 'init-1', }, new URL(GAME_FRAME).origin, ); ``` 调用其他方法时只需更换 `method` 和 `args`: ```ts // 相当于 window.CocosGameContainer.openMenu() this.callWebContainer('openMenu'); // 相当于 window.CocosGameContainer.openGift(payload) this.callWebContainer('openGift', [{ title: '新手礼包', code: 'WELCOME' }]); ``` 网页执行后会向 Cocos 父窗口回复: ```js { type: 'game-container:result', method: 'openMenu', requestId: '...', ok: true } ``` `useGameIFrame` 完成 `window.CocosGameContainer` 注册后,会触发浏览器事件 `game-container:ready`。页面 URL 显式开启 Scheme Bridge 时,会向 Cocos 转发 `game_ready`: ```text https://container.example.com/index.html?scheme=game2c ``` 转发结果: ```text game2c://message?cmd=game_ready ``` Cocos 应先注册 `game2c` Scheme 回调,再加载带 `scheme=game2c` 的页面;收到 `game_ready` 后即可安全调用 `window.CocosGameContainer.init(...)`。`scheme` 参数未传或为空时不会启用自定义协议,而是通过 `window.parent.postMessage({ cmd: 'game_ready' }, '*')` 转发。 ## iframe → Cocos 第三方游戏发送: ```js window.parent.postMessage( { type: 'GAME_EVENT', event: 'level_complete', score: 100 }, 'https://container.example.com' ); ``` `useGameIFrame` 同时负责注册 `CocosGameContainerApi`、监听 iframe 消息、将对象消息序列化为 JSON,并根据 `enableSchemeBridge` 选择转发方式。 开启 Scheme Bridge 时: ```text game2c://message?cmd= ``` Cocos 收到 URL 后需要读取 `cmd` 参数并执行 URL 解码,如果内容是 JSON 再执行 `JSON.parse`。 未开启 Scheme Bridge 时: ```js window.parent.postMessage({ cmd: serializedMessage }, '*'); ``` 点击菜单中的“返回大厅”会发送: ```text game2c://message?cmd=exitGame ``` ## 弹窗管理 弹窗状态集中在 `src/stores/useModalStore.ts`,使用 Zustand 管理。`ModalHost` 负责渲染当前弹窗,所有弹窗共用居中布局、遮罩和开关动画。 增加新弹窗时: 1. 在 `src/components/dialogs` 创建弹窗内容组件和 `styles.module.scss`。 2. 在 `useModalStore.ts` 注册弹窗类型与打开方法。 3. 在 `ModalHost.tsx` 增加内容映射。