FEAT => 本次更新项目为:

基础通信搞定了
This commit is contained in:
超级老白兔
2025-08-01 16:29:34 +08:00
parent 325d53cad6
commit fddda27ca8
11 changed files with 1179 additions and 41 deletions

1
ckApp/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
unpackage

View File

@@ -3,13 +3,13 @@
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "uni-app"
"navigationBarTitleText": "",
"navigationStyle": "custom"
}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
},

View File

@@ -1,8 +1,33 @@
<template>
<view class="content">
<image class="logo" src="/static/logo.png"></image>
<view class="text-area">
<text class="title">{{title}}</text>
<view class="header">
123
</view>
<!-- iframe 容器 -->
<view class="iframe-container" :class="'iframe-' + iframeSize">
<web-view
ref="webviewRef"
:src="iframeUrl"
@message="handleMessage"
:fullscreen="false"
></web-view>
</view>
<!-- 控制按钮 -->
<view class="controls">
<button @click="sendMessageToIframe" class="btn">发送消息到iframe</button>
<button @click="toggleIframeSize" class="btn btn-secondary">切换iframe大小</button>
</view>
<!-- 消息显示区域 -->
<view class="message-area">
<text class="message-title">接收到的消息</text>
<view class="message-list">
<view v-for="(msg, index) in receivedMessages" :key="index" class="message-item">
<text class="message-text">{{msg}}</text>
</view>
</view>
</view>
</view>
</template>
@@ -11,42 +36,287 @@
export default {
data() {
return {
title: 'Hello'
title: 'iframe 通信示例',
// iframeUrl: 'http://localhost:3000/iframe',
iframeUrl: 'https://kr-op.quwanzhi.com/iframe',
receivedMessages: [],
messageId: 0,
iframeSize: 'medium' // 控制 iframe 大小small, medium, large
}
},
onLoad() {
// 页面加载时的初始化
console.log('页面加载完成');
},
methods: {
}
// 接收 web-view 发送的消息
handleMessage(event) {
// 消息在 event.detail.data 中(是一个数组,取最后一条)
const webData = event.detail.data[0];
console.log('App 收到 web-view 消息:', webData);
// 将消息添加到显示列表
this.receivedMessages.push(`[${new Date().toLocaleTimeString()}] ${JSON.stringify(webData)}`);
// 根据消息类型处理逻辑
if (webData.type === 'ready') {
console.log('web-view 已准备就绪');
uni.showToast({
title: 'web-view 连接成功',
icon: 'success'
});
} else if (webData.type === 'toApp') {
uni.showToast({
title: `收到:${webData.content}`,
icon: 'none'
});
} else if (webData.type === 'data') {
console.log('收到数据:', webData.data);
}
},
// App 发送消息到 web-view
sendMessageToIframe() {
this.messageId++;
const message = {
id: this.messageId,
type: 'fromApp',
content: `Hello我是 App 发送的消息 ${this.messageId}`,
timestamp: Date.now()
};
// 通过 evalJS 发送消息到 web-view
this.sendMessageToWebView(message);
},
// App 向 web-view 发送消息
sendMessageToWebView(message) {
// 通过 ref 获取 web-view 实例,调用 evalJS 执行 web-view 中的函数
// 注意:需将数据转为字符串(避免语法错误)
if (this.$refs.webviewRef && this.$refs.webviewRef.evalJS) {
try {
this.$refs.webviewRef.evalJS(`receiveFromApp(${JSON.stringify(message)})`);
console.log('App 发送消息到 web-view', message);
} catch (e) {
console.error('evalJS 执行失败:', e);
}
} else {
console.error('web-view ref 不存在或 evalJS 方法不可用');
}
},
// 移除 localStorage 相关代码,使用 postMessage 通信
// 切换 iframe 大小
toggleIframeSize() {
const sizes = ['small', 'medium', 'large'];
const currentIndex = sizes.indexOf(this.iframeSize);
const nextIndex = (currentIndex + 1) % sizes.length;
this.iframeSize = sizes[nextIndex];
console.log('iframe 大小切换为:', this.iframeSize);
}
},
// 移除 mounted 生命周期,因为 uni-app 中可能不支持
// 移除 onUnload因为不再需要清理定时器
}
</script>
<style>
<style lang="scss" scoped>
// 主容器
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #f8f9fa;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
// 头部区域
.header {
height: 46rpx;
background: #fff;
}
.text-area {
// iframe 容器
.iframe-container {
overflow: hidden;
background: white;
position: relative;
margin: 20rpx;
border-radius: 20rpx;
box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
// 针对 web-view 的特殊样式
:deep(web-view) {
width: 100% !important;
height: 100% !important;
border: none !important;
outline: none !important;
box-shadow: none !important;
}
// 兼容不同平台的 web-view 样式
:deep(iframe) {
border: none !important;
outline: none !important;
box-shadow: none !important;
}
// 不同大小的样式
&.iframe-small {
height: 300rpx;
min-height: 300rpx;
}
&.iframe-medium {
height: 500rpx;
min-height: 500rpx;
}
&.iframe-large {
height: 700rpx;
min-height: 700rpx;
}
}
// 控制按钮区域
.controls {
display: flex;
justify-content: center;
gap: 20rpx;
padding: 20rpx;
background: white;
border-bottom: 2rpx solid #f0f0f0;
flex-wrap: wrap;
}
.title {
font-size: 36rpx;
color: #8f8f94;
.btn {
flex: 1;
background: linear-gradient(135deg, #188eee 0%, #096dd9 100%);
color: white;
border: none;
border-radius: 20rpx;
padding: 24rpx 20rpx;
font-size: 28rpx;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4rpx 12rpx rgba(24, 142, 238, 0.3);
&:active {
transform: translateY(2rpx);
box-shadow: 0 2rpx 8rpx rgba(24, 142, 238, 0.4);
}
&:hover {
background: linear-gradient(135deg, #096dd9 0%, #0050b3 100%);
}
}
// 消息显示区域
.message-area {
flex: 1;
padding: 20rpx;
background: white;
overflow: hidden;
display: flex;
flex-direction: column;
}
.message-title {
font-size: 28rpx;
color: #333;
margin-bottom: 20rpx;
display: block;
font-weight: 600;
border-bottom: 2rpx solid #f0f0f0;
padding-bottom: 16rpx;
}
.message-list {
flex: 1;
overflow-y: auto;
border: 2rpx solid #f0f0f0;
border-radius: 16rpx;
padding: 16rpx;
background: #fafafa;
// 自定义滚动条
&::-webkit-scrollbar {
width: 8rpx;
}
&::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 4rpx;
}
&::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 4rpx;
&:hover {
background: #a8a8a8;
}
}
}
.message-item {
background: white;
padding: 20rpx;
margin-bottom: 16rpx;
border-radius: 12rpx;
border-left: 6rpx solid #188eee;
box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
transition: all 0.3s ease;
&:last-child {
margin-bottom: 0;
}
&:hover {
transform: translateX(4rpx);
box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.12);
}
}
.message-text {
font-size: 24rpx;
color: #333;
word-break: break-all;
line-height: 1.5;
font-family: "Courier New", monospace;
}
// 响应式设计
@media (max-width: 768rpx) {
.content {
padding: 0;
}
.iframe-container {
margin: 16rpx;
border-radius: 16rpx;
}
.controls {
padding: 16rpx;
gap: 16rpx;
}
.btn {
padding: 20rpx 16rpx;
font-size: 26rpx;
}
.message-area {
padding: 16rpx;
}
.message-item {
padding: 16rpx;
margin-bottom: 12rpx;
}
}
</style>

0
ckApp/utils/config.js Normal file
View File

View File

@@ -1,13 +1,19 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Nkebao Base</title>
<style>html{font-size:16px;}</style>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Nkebao Base</title>
<style>
html {
font-size: 16px;
}
</style>
<!-- 引入 uni-app web-view SDK必须 -->
<script src="./websdk.js"></script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

308
nkebao/public/websdk.js Normal file
View File

@@ -0,0 +1,308 @@
!(function (e, n) {
"object" == typeof exports && "undefined" != typeof module
? (module.exports = n())
: "function" == typeof define && define.amd
? define(n)
: ((e = e || self).uni = n());
})(this, function () {
"use strict";
try {
var e = {};
(Object.defineProperty(e, "passive", {
get: function () {
!0;
},
}),
window.addEventListener("test-passive", null, e));
} catch (e) {}
var n = Object.prototype.hasOwnProperty;
function i(e, i) {
return n.call(e, i);
}
var t = [];
function o() {
return window.__dcloud_weex_postMessage || window.__dcloud_weex_;
}
function a() {
return window.__uniapp_x_postMessage || window.__uniapp_x_;
}
var r = function (e, n) {
var i = { options: { timestamp: +new Date() }, name: e, arg: n };
if (a()) {
if ("postMessage" === e) {
var r = { data: n };
return window.__uniapp_x_postMessage
? window.__uniapp_x_postMessage(r)
: window.__uniapp_x_.postMessage(JSON.stringify(r));
}
var d = {
type: "WEB_INVOKE_APPSERVICE",
args: { data: i, webviewIds: t },
};
window.__uniapp_x_postMessage
? window.__uniapp_x_postMessageToService(d)
: window.__uniapp_x_.postMessageToService(JSON.stringify(d));
} else if (o()) {
if ("postMessage" === e) {
var s = { data: [n] };
return window.__dcloud_weex_postMessage
? window.__dcloud_weex_postMessage(s)
: window.__dcloud_weex_.postMessage(JSON.stringify(s));
}
var w = {
type: "WEB_INVOKE_APPSERVICE",
args: { data: i, webviewIds: t },
};
window.__dcloud_weex_postMessage
? window.__dcloud_weex_postMessageToService(w)
: window.__dcloud_weex_.postMessageToService(JSON.stringify(w));
} else {
if (!window.plus)
return window.parent.postMessage(
{ type: "WEB_INVOKE_APPSERVICE", data: i, pageId: "" },
"*",
);
if (0 === t.length) {
var u = plus.webview.currentWebview();
if (!u) throw new Error("plus.webview.currentWebview() is undefined");
var g = u.parent(),
v = "";
((v = g ? g.id : u.id), t.push(v));
}
if (plus.webview.getWebviewById("__uniapp__service"))
plus.webview.postMessageToUniNView(
{ type: "WEB_INVOKE_APPSERVICE", args: { data: i, webviewIds: t } },
"__uniapp__service",
);
else {
var c = JSON.stringify(i);
plus.webview
.getLaunchWebview()
.evalJS(
'UniPlusBridge.subscribeHandler("'
.concat("WEB_INVOKE_APPSERVICE", '",')
.concat(c, ",")
.concat(JSON.stringify(t), ");"),
);
}
}
},
d = {
navigateTo: function () {
var e =
arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
n = e.url;
r("navigateTo", { url: encodeURI(n) });
},
navigateBack: function () {
var e =
arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
n = e.delta;
r("navigateBack", { delta: parseInt(n) || 1 });
},
switchTab: function () {
var e =
arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
n = e.url;
r("switchTab", { url: encodeURI(n) });
},
reLaunch: function () {
var e =
arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
n = e.url;
r("reLaunch", { url: encodeURI(n) });
},
redirectTo: function () {
var e =
arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {},
n = e.url;
r("redirectTo", { url: encodeURI(n) });
},
getEnv: function (e) {
a()
? e({ uvue: !0 })
: o()
? e({ nvue: !0 })
: window.plus
? e({ plus: !0 })
: e({ h5: !0 });
},
postMessage: function () {
var e =
arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
r("postMessage", e.data || {});
},
},
s = /uni-app/i.test(navigator.userAgent),
w = /Html5Plus/i.test(navigator.userAgent),
u = /complete|loaded|interactive/;
var g =
window.my &&
navigator.userAgent.indexOf(
["t", "n", "e", "i", "l", "C", "y", "a", "p", "i", "l", "A"]
.reverse()
.join(""),
) > -1;
var v =
window.swan && window.swan.webView && /swan/i.test(navigator.userAgent);
var c =
window.qq &&
window.qq.miniProgram &&
/QQ/i.test(navigator.userAgent) &&
/miniProgram/i.test(navigator.userAgent);
var p =
window.tt &&
window.tt.miniProgram &&
/toutiaomicroapp/i.test(navigator.userAgent);
var _ =
window.wx &&
window.wx.miniProgram &&
/micromessenger/i.test(navigator.userAgent) &&
/miniProgram/i.test(navigator.userAgent);
var m = window.qa && /quickapp/i.test(navigator.userAgent);
var f =
window.ks &&
window.ks.miniProgram &&
/micromessenger/i.test(navigator.userAgent) &&
/miniProgram/i.test(navigator.userAgent);
var l =
window.tt &&
window.tt.miniProgram &&
/Lark|Feishu/i.test(navigator.userAgent);
var E =
window.jd && window.jd.miniProgram && /jdmp/i.test(navigator.userAgent);
var x =
window.xhs &&
window.xhs.miniProgram &&
/xhsminiapp/i.test(navigator.userAgent);
for (
var S,
h = function () {
((window.UniAppJSBridge = !0),
document.dispatchEvent(
new CustomEvent("UniAppJSBridgeReady", {
bubbles: !0,
cancelable: !0,
}),
));
},
y = [
function (e) {
if (s || w)
return (
window.__uniapp_x_postMessage ||
window.__uniapp_x_ ||
window.__dcloud_weex_postMessage ||
window.__dcloud_weex_
? document.addEventListener("DOMContentLoaded", e)
: window.plus && u.test(document.readyState)
? setTimeout(e, 0)
: document.addEventListener("plusready", e),
d
);
},
function (e) {
if (_)
return (
window.WeixinJSBridge && window.WeixinJSBridge.invoke
? setTimeout(e, 0)
: document.addEventListener("WeixinJSBridgeReady", e),
window.wx.miniProgram
);
},
function (e) {
if (c)
return (
window.QQJSBridge && window.QQJSBridge.invoke
? setTimeout(e, 0)
: document.addEventListener("QQJSBridgeReady", e),
window.qq.miniProgram
);
},
function (e) {
if (g) {
document.addEventListener("DOMContentLoaded", e);
var n = window.my;
return {
navigateTo: n.navigateTo,
navigateBack: n.navigateBack,
switchTab: n.switchTab,
reLaunch: n.reLaunch,
redirectTo: n.redirectTo,
postMessage: n.postMessage,
getEnv: n.getEnv,
};
}
},
function (e) {
if (v)
return (
document.addEventListener("DOMContentLoaded", e),
window.swan.webView
);
},
function (e) {
if (p)
return (
document.addEventListener("DOMContentLoaded", e),
window.tt.miniProgram
);
},
function (e) {
if (m) {
window.QaJSBridge && window.QaJSBridge.invoke
? setTimeout(e, 0)
: document.addEventListener("QaJSBridgeReady", e);
var n = window.qa;
return {
navigateTo: n.navigateTo,
navigateBack: n.navigateBack,
switchTab: n.switchTab,
reLaunch: n.reLaunch,
redirectTo: n.redirectTo,
postMessage: n.postMessage,
getEnv: n.getEnv,
};
}
},
function (e) {
if (f)
return (
window.WeixinJSBridge && window.WeixinJSBridge.invoke
? setTimeout(e, 0)
: document.addEventListener("WeixinJSBridgeReady", e),
window.ks.miniProgram
);
},
function (e) {
if (l)
return (
document.addEventListener("DOMContentLoaded", e),
window.tt.miniProgram
);
},
function (e) {
if (E)
return (
window.JDJSBridgeReady && window.JDJSBridgeReady.invoke
? setTimeout(e, 0)
: document.addEventListener("JDJSBridgeReady", e),
window.jd.miniProgram
);
},
function (e) {
if (x) return window.xhs.miniProgram;
},
function (e) {
return (document.addEventListener("DOMContentLoaded", e), d);
},
],
M = 0;
M < y.length && !(S = y[M](h));
M++
);
S || (S = {});
var P = "undefined" != typeof uni ? uni : {};
if (!P.navigateTo) for (var b in S) i(S, b) && (P[b] = S[b]);
return ((P.webView = S), P);
});

View File

@@ -2,7 +2,6 @@ import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import "./styles/global.scss";
// import VConsole from "vconsole";
// new VConsole();
const root = createRoot(document.getElementById("root")!);

View File

@@ -0,0 +1,278 @@
.iframe-debug-page {
min-height: 100vh;
background: var(--primary-gradient);
padding: 20px;
font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
.header {
text-align: center;
color: white;
margin-bottom: 30px;
h1 {
font-size: 2.5rem;
margin: 0 0 10px 0;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
p {
font-size: 1.1rem;
margin: 0;
opacity: 0.9;
}
}
.content {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 30px;
margin-bottom: 30px;
@media (max-width: 768px) {
grid-template-columns: 1fr;
gap: 20px;
}
}
.control-panel,
.message-panel {
background: white;
border-radius: 15px;
padding: 25px;
box-shadow: 0 10px 30px var(--primary-shadow);
h3 {
margin: 0 0 20px 0;
color: #333;
font-size: 1.3rem;
border-bottom: 2px solid var(--primary-color);
padding-bottom: 10px;
}
}
.input-group {
display: flex;
gap: 10px;
margin-bottom: 20px;
@media (max-width: 480px) {
flex-direction: column;
}
}
.message-input {
flex: 1;
padding: 12px 15px;
border: 2px solid #e1e5e9;
border-radius: 8px;
font-size: 1rem;
transition: border-color 0.3s ease;
&:focus {
outline: none;
border-color: var(--primary-color);
box-shadow: 0 0 0 3px var(--primary-shadow-light);
}
}
.button-group {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.btn {
padding: 12px 20px;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
text-transform: uppercase;
letter-spacing: 0.5px;
&:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}
&:active {
transform: translateY(0);
}
&.btn-primary {
background: var(--primary-gradient);
color: white;
&:hover {
background: linear-gradient(
135deg,
var(--primary-color-dark) 0%,
var(--primary-color) 100%
);
}
}
&.btn-secondary {
background: linear-gradient(
135deg,
var(--primary-color-light) 0%,
var(--primary-color) 100%
);
color: white;
&:hover {
background: linear-gradient(
135deg,
var(--primary-color) 0%,
var(--primary-color-dark) 100%
);
}
}
&.btn-danger {
background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
color: white;
&:hover {
background: linear-gradient(135deg, #ee5a52 0%, #d63031 100%);
}
}
}
.message-list {
max-height: 400px;
overflow-y: auto;
border: 1px solid #e1e5e9;
border-radius: 8px;
padding: 10px;
background: #f8f9fa;
}
.no-messages {
text-align: center;
color: #6c757d;
font-style: italic;
padding: 20px;
}
.message-item {
background: white;
padding: 12px 15px;
margin-bottom: 8px;
border-radius: 6px;
border-left: 4px solid var(--primary-color);
box-shadow: 0 2px 4px var(--primary-shadow-light);
&:last-child {
margin-bottom: 0;
}
}
.message-text {
font-family: "Courier New", monospace;
font-size: 0.9rem;
color: #333;
word-break: break-all;
line-height: 1.4;
}
.info-panel {
background: white;
border-radius: 15px;
padding: 25px;
box-shadow: 0 10px 30px var(--primary-shadow);
h3 {
margin: 0 0 20px 0;
color: #333;
font-size: 1.3rem;
border-bottom: 2px solid var(--primary-color);
padding-bottom: 10px;
}
}
.info-item {
margin-bottom: 12px;
padding: 10px;
background: #f8f9fa;
border-radius: 6px;
border-left: 3px solid var(--primary-color);
strong {
color: #495057;
margin-right: 8px;
}
&:last-child {
margin-bottom: 0;
}
}
// 滚动条样式
.message-list::-webkit-scrollbar {
width: 8px;
}
.message-list::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 4px;
}
.message-list::-webkit-scrollbar-thumb {
background: #c1c1c1;
border-radius: 4px;
&:hover {
background: #a8a8a8;
}
}
// 响应式设计
@media (max-width: 768px) {
.iframe-debug-page {
padding: 15px;
}
.header h1 {
font-size: 2rem;
}
.control-panel,
.message-panel,
.info-panel {
padding: 20px;
}
.btn {
padding: 10px 16px;
font-size: 0.9rem;
}
}
@media (max-width: 480px) {
.header h1 {
font-size: 1.8rem;
}
.content {
gap: 15px;
}
.control-panel,
.message-panel,
.info-panel {
padding: 15px;
}
.button-group {
flex-direction: column;
}
.btn {
width: 100%;
}
}

View File

@@ -0,0 +1,264 @@
import React, { useState, useEffect, useRef } from "react";
import style from "./index.module.scss";
// 声明全局的 uni 对象
declare global {
interface Window {
uni: any;
}
}
interface Message {
id: number;
type: string;
data: any;
timestamp: number;
}
const IframeDebugPage: React.FC = () => {
const [receivedMessages, setReceivedMessages] = useState<string[]>([]);
const [messageId, setMessageId] = useState(0);
const [inputMessage, setInputMessage] = useState("");
useEffect(() => {
// 初始化 uni-app web-view SDK
const initUniSDK = () => {
console.log("web-view SDK 初始化完成");
// 页面加载完成后发送准备就绪消息
setTimeout(() => {
sendMessageToParent({
id: 0,
type: "ready",
data: { status: "loaded", url: window.location.href },
timestamp: Date.now(),
});
}, 500);
};
// 监听 SDK 初始化完成事件
document.addEventListener("UniAppJSBridgeReady", initUniSDK);
// 检查URL参数中的消息
checkUrlMessage();
// 监听 postMessage 事件(备用方案)
const handlePostMessage = (event: MessageEvent) => {
console.log("收到 postMessage:", event.data);
// 处理 uni.postMessage 发送的消息格式
if (event.data && typeof event.data === "object") {
// uni.postMessage 发送的消息格式是 { data: message }
if (event.data.data) {
handleParentMessage(event.data.data);
} else {
// 直接发送的消息格式
handleParentMessage(event.data);
}
}
};
window.addEventListener("message", handlePostMessage);
return () => {
document.removeEventListener("UniAppJSBridgeReady", initUniSDK);
window.removeEventListener("message", handlePostMessage);
};
}, []);
// 检查URL参数中的消息
const checkUrlMessage = () => {
const urlParams = new URLSearchParams(window.location.search);
const messageParam = urlParams.get("message");
if (messageParam) {
try {
const message = JSON.parse(decodeURIComponent(messageParam));
handleParentMessage(message);
// 清除URL参数
const newUrl = window.location.pathname;
window.history.replaceState({}, "", newUrl);
} catch (e) {
console.error("解析URL消息失败:", e);
}
}
};
// 移除 localStorage 相关代码,使用 postMessage 通信
// 接收 App 发送的消息(需与 App 端 evalJS 调用的函数名一致)
const receiveFromApp = (data: any) => {
console.log("web-view 收到 App 消息:", data);
handleParentMessage(data);
};
// 将函数挂载到全局,供 App 端调用
useEffect(() => {
(window as any).receiveFromApp = receiveFromApp;
return () => {
delete (window as any).receiveFromApp;
};
}, []);
// 接收 App 发送的消息
const handleParentMessage = (message: Message) => {
console.log("web-view 收到 App 消息:", message);
const messageText = `[${new Date().toLocaleTimeString()}] 收到: ${JSON.stringify(message)}`;
setReceivedMessages(prev => [...prev, messageText]);
// 根据消息类型进行不同处理
if (message.type === "command") {
if (message.data?.action === "update") {
// 更新页面内容
console.log("执行更新操作:", message.data.content);
}
} else if (message.type === "fromApp") {
console.log("收到 App 消息:", message.data?.content);
}
};
// 向 App 发送消息
const sendMessageToParent = (message: Message) => {
console.log("web-view 发送消息到 App:", message);
// 通过 uni.postMessage 发送消息(数据必须放在 data 字段中)
if (window.uni && window.uni.postMessage) {
try {
window.uni.postMessage({
data: message,
});
console.log("通过 uni.postMessage 发送消息到 App:", message);
} catch (e) {
console.error("uni.postMessage 失败:", e);
}
} else {
console.error("uni 对象不存在,无法发送消息");
}
};
// 向 App 发送消息
const sendCustomMessage = () => {
if (!inputMessage.trim()) return;
const newMessageId = messageId + 1;
setMessageId(newMessageId);
const message: Message = {
id: newMessageId,
type: "toApp",
data: {
content: inputMessage,
source: "web-view",
timestamp: Date.now(),
},
timestamp: Date.now(),
};
sendMessageToParent(message);
setInputMessage("");
};
// 发送测试消息到 App
const sendTestMessage = () => {
const newMessageId = messageId + 1;
setMessageId(newMessageId);
const message: Message = {
id: newMessageId,
type: "toApp",
data: {
action: "ping",
content: `web-view测试消息 ${newMessageId}`,
random: Math.random(),
},
timestamp: Date.now(),
};
sendMessageToParent(message);
};
// 清空消息列表
const clearMessages = () => {
setInputMessage("");
setReceivedMessages([]);
};
return (
<div className={style["iframe-debug-page"]}>
<div className={style.header}>
<h1>iframe </h1>
<p>: {new Date().toLocaleString()}</p>
</div>
<div className={style.content}>
<div className={style["control-panel"]}>
<h3></h3>
<div className={style["input-group"]}>
<input
type="text"
value={inputMessage}
onChange={e => setInputMessage(e.target.value)}
placeholder="输入要发送的消息"
className={style["message-input"]}
/>
<button
onClick={sendCustomMessage}
className={`${style.btn} ${style["btn-primary"]}`}
>
</button>
</div>
<div className={style["button-group"]}>
<button
onClick={sendTestMessage}
className={`${style.btn} ${style["btn-secondary"]}`}
>
</button>
<button
onClick={clearMessages}
className={`${style.btn} ${style["btn-danger"]}`}
>
</button>
</div>
</div>
<div className={style["message-panel"]}>
<h3> ({receivedMessages.length})</h3>
<div className={style["message-list"]}>
{receivedMessages.length === 0 ? (
<div className={style["no-messages"]}></div>
) : (
receivedMessages.map((msg, index) => (
<div key={index} className={style["message-item"]}>
<span className={style["message-text"]}>{msg}</span>
</div>
))
)}
</div>
</div>
</div>
<div className={style["info-panel"]}>
<h3></h3>
<div className={style["info-item"]}>
<strong>URL:</strong> {window.location.href}
</div>
<div className={style["info-item"]}>
<strong>User Agent:</strong> {navigator.userAgent}
</div>
<div className={style["info-item"]}>
<strong>:</strong> {window.innerWidth} x {window.innerHeight}
</div>
<div className={style["info-item"]}>
<strong>ID:</strong> {messageId}
</div>
</div>
</div>
);
};
export default IframeDebugPage;

View File

@@ -0,0 +1,12 @@
import IframeDebugPage from "@/pages/iframe";
// iframe 调试路由
const iframeRoutes = [
{
path: "/iframe",
element: <IframeDebugPage />,
auth: false, // 不需要认证,方便调试
},
];
export default iframeRoutes;

View File

@@ -36,9 +36,9 @@ export const ENV_INFO = {
// 开发环境检查
export const checkDevEnvironment = () => {
if (isDevelopment) {
console.log("🚀 开发环境已启用");
console.log("📋 环境信息:", ENV_INFO);
console.log("⚙️ 开发特性:", DEV_FEATURES);
// console.log("🚀 开发环境已启用");
// console.log("📋 环境信息:", ENV_INFO);
// console.log("⚙️ 开发特性:", DEV_FEATURES);
}
};