diff --git a/ckApp/.gitignore b/ckApp/.gitignore
new file mode 100644
index 00000000..efe77355
--- /dev/null
+++ b/ckApp/.gitignore
@@ -0,0 +1 @@
+unpackage
\ No newline at end of file
diff --git a/ckApp/pages.json b/ckApp/pages.json
index 869105d7..21b4384c 100644
--- a/ckApp/pages.json
+++ b/ckApp/pages.json
@@ -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"
},
diff --git a/ckApp/pages/index/index.vue b/ckApp/pages/index/index.vue
index ec0ec260..5756d34f 100644
--- a/ckApp/pages/index/index.vue
+++ b/ckApp/pages/index/index.vue
@@ -1,8 +1,33 @@
-
-
- {{title}}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 接收到的消息:
+
+
+ {{msg}}
+
+
@@ -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,因为不再需要清理定时器
}
-
diff --git a/ckApp/utils/config.js b/ckApp/utils/config.js
new file mode 100644
index 00000000..e69de29b
diff --git a/nkebao/index.html b/nkebao/index.html
index 2aaa892e..d1b033c9 100644
--- a/nkebao/index.html
+++ b/nkebao/index.html
@@ -1,13 +1,19 @@
-
-
-
-
-
- Nkebao Base
-
-
-
-
-
-
-
\ No newline at end of file
+
+
+
+
+
+ Nkebao Base
+
+
+
+
+
+
+
+
+
diff --git a/nkebao/public/websdk.js b/nkebao/public/websdk.js
new file mode 100644
index 00000000..99870fa4
--- /dev/null
+++ b/nkebao/public/websdk.js
@@ -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);
+});
diff --git a/nkebao/src/main.tsx b/nkebao/src/main.tsx
index d88f0e11..f4ae337c 100644
--- a/nkebao/src/main.tsx
+++ b/nkebao/src/main.tsx
@@ -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")!);
diff --git a/nkebao/src/pages/iframe/index.module.scss b/nkebao/src/pages/iframe/index.module.scss
new file mode 100644
index 00000000..e18c1633
--- /dev/null
+++ b/nkebao/src/pages/iframe/index.module.scss
@@ -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%;
+ }
+}
diff --git a/nkebao/src/pages/iframe/index.tsx b/nkebao/src/pages/iframe/index.tsx
new file mode 100644
index 00000000..c3c4c358
--- /dev/null
+++ b/nkebao/src/pages/iframe/index.tsx
@@ -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([]);
+ 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 (
+
+
+
iframe 通信调试页面
+
当前时间: {new Date().toLocaleString()}
+
+
+
+
+
控制面板
+
+
+ setInputMessage(e.target.value)}
+ placeholder="输入要发送的消息"
+ className={style["message-input"]}
+ />
+
+
+
+
+
+
+
+
+
+
+
接收到的消息 ({receivedMessages.length})
+
+ {receivedMessages.length === 0 ? (
+
暂无消息
+ ) : (
+ receivedMessages.map((msg, index) => (
+
+ {msg}
+
+ ))
+ )}
+
+
+
+
+
+
页面信息
+
+ 页面URL: {window.location.href}
+
+
+ User Agent: {navigator.userAgent}
+
+
+ 窗口大小: {window.innerWidth} x {window.innerHeight}
+
+
+ 消息ID: {messageId}
+
+
+
+ );
+};
+
+export default IframeDebugPage;
diff --git a/nkebao/src/router/module/iframe.tsx b/nkebao/src/router/module/iframe.tsx
new file mode 100644
index 00000000..32af69e2
--- /dev/null
+++ b/nkebao/src/router/module/iframe.tsx
@@ -0,0 +1,12 @@
+import IframeDebugPage from "@/pages/iframe";
+
+// iframe 调试路由
+const iframeRoutes = [
+ {
+ path: "/iframe",
+ element: ,
+ auth: false, // 不需要认证,方便调试
+ },
+];
+
+export default iframeRoutes;
diff --git a/nkebao/src/utils/env.ts b/nkebao/src/utils/env.ts
index f0bdd0d5..d80a41f2 100644
--- a/nkebao/src/utils/env.ts
+++ b/nkebao/src/utils/env.ts
@@ -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);
}
};