关闭页面Flutter通道处理完成

This commit is contained in:
tianfeng 2025-08-15 18:49:36 +08:00
parent 3b567b1da3
commit c383958a80
3 changed files with 226 additions and 41 deletions

View File

@ -1,6 +1,6 @@
<template>
<div class="mobile-header">
<button v-if="showBack" class="back-btn" @click="goBack">
<button v-if="showBack" class="back-btn" @click="handleBack">
<span></span>
</button>
<h1 class="title">{{ title }}</h1>
@ -12,10 +12,11 @@
</template>
<script setup>
import { useRouter } from 'vue-router'
import { useRouter, useRoute } from 'vue-router'
import { closePage, handleBackButton, isInApp } from '../utils/appBridge.js'
// props
defineProps({
const props = defineProps({
title: {
type: String,
required: true
@ -27,6 +28,10 @@ defineProps({
showHelp: {
type: Boolean,
default: false
},
isHomePage: {
type: Boolean,
default: false
}
})
@ -34,9 +39,18 @@ defineProps({
defineEmits(['help'])
const router = useRouter()
const route = useRoute()
const goBack = () => {
router.go(-1)
const handleBack = () => {
if (props.isHomePage && isInApp()) {
// APP
console.debug('首页返回:关闭页面')
closePage()
} else {
//
console.debug('正常返回')
router.go(-1)
}
}
</script>

View File

@ -24,7 +24,62 @@ export function android() {
* @returns {boolean}
*/
export function isInApp() {
return !!(window.app || window.webkit)
return !!(window.app || window.webkit || window.FlutterPageControl)
}
/**
* 关闭当前页面返回到Flutter上一页
*/
export function closePage() {
try {
if (window.app && window.app.closePage) {
// 使用注入的方法
window.app.closePage()
} else if (window.FlutterPageControl) {
// 直接使用Flutter通道
window.FlutterPageControl.postMessage('close_page')
} else {
// 降级处理:浏览器环境
if (window.history.length > 1) {
window.history.back()
} else {
window.close()
}
}
} catch (error) {
console.error('关闭页面失败:', error)
// 降级处理
window.history.back()
}
}
/**
* 退出APP
*/
export function exitApp() {
try {
if (window.app && window.app.exitApp) {
window.app.exitApp()
} else if (window.FlutterPageControl) {
window.FlutterPageControl.postMessage('exit_app')
}
} catch (error) {
console.error('退出APP失败:', error)
}
}
/**
* 处理返回按钮逻辑
* @param {boolean} isHomePage 是否为首页
*/
export function handleBackButton(isHomePage = false) {
if (isHomePage) {
// 首页返回:关闭页面
closePage()
} else {
// 非首页:正常返回
window.history.back()
}
}
/**
@ -38,6 +93,7 @@ export function connectApplication(renderFun) {
try {
if (ios()) {
console.debug('ios access detected')
// iOS可能需要特殊处理这里先使用通用方法
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.getAccessOrigin) {
window.webkit.messageHandlers.getAccessOrigin.postMessage({})
@ -45,11 +101,82 @@ export function connectApplication(renderFun) {
renderFun(window.app.getAccessOrigin())
}
} else if (android()) {
// Android处理
if (window.app && window.app.getAccessOrigin) {
renderFun(window.app.getAccessOrigin())
console.debug('Flutter Android WebView 检测')
console.debug('window.app 对象:', window.app)
// 检查Flutter注入的接口
if (window.app) {
console.debug('window.app 的所有方法:')
console.debug(Object.keys(window.app))
// 检查具体的方法
console.debug('getAccessOrigin 方法存在?', typeof window.app.getAccessOrigin)
console.debug('getAccessOrigin 是函数?', typeof window.app.getAccessOrigin === 'function')
}
// 等待Flutter注入完成
const waitForFlutterInterface = () => {
let attempts = 0;
const maxAttempts = 50; // 最多等待5秒
const checkInterface = () => {
attempts++;
console.debug(`尝试第 ${attempts} 次检查Flutter接口...`)
if (window.app && window.app.getAccessOrigin && typeof window.app.getAccessOrigin === 'function') {
console.debug('Flutter接口检测成功调用 getAccessOrigin')
try {
const result = window.app.getAccessOrigin()
console.debug('getAccessOrigin 返回结果:', result)
renderFun(result)
} catch (error) {
console.error('调用 getAccessOrigin 出错:', error)
}
} else if (attempts < maxAttempts) {
// 继续等待
setTimeout(checkInterface, 100)
} else {
console.error('Flutter接口注入超时使用默认数据')
// 使用默认的开发数据
const mockAccess = JSON.stringify({
'Authorization': 'Bearer FLUTTER_MOCK_TOKEN',
'Req-Lang': 'en',
'Req-App-Intel': 'build=1.0;version=2.1;channel=flutter;Req-Imei=flutter-device',
'Req-Sys-Origin': 'origin=LIKEI;originChild=LIKEI'
})
renderFun(mockAccess)
}
}
checkInterface()
}
// 如果window.app已存在直接检查否则等待
if (window.app) {
waitForFlutterInterface()
} else {
console.debug('等待Flutter注入window.app...')
// 监听window.app的创建
let checkCount = 0
const checkApp = () => {
checkCount++
if (window.app) {
console.debug('检测到window.app开始连接')
waitForFlutterInterface()
} else if (checkCount < 50) {
setTimeout(checkApp, 100)
} else {
console.error('等待window.app超时')
// 手动通知Flutter注入接口
if (window.FlutterApp && window.FlutterApp.postMessage) {
window.FlutterApp.postMessage('requestAccessOrigin')
}
}
}
checkApp()
}
} else {
console.debug('非移动设备环境')
// 非APP环境可能是浏览器调试
console.warn('Not in APP environment, using mock data for development')
// 开发环境可以提供模拟数据
@ -151,9 +278,9 @@ export function setHttpHeaders(headerInfo) {
console.error('Failed to update HTTP headers:', error)
})
console.log('🔑 Authorization token set:', headerInfo.authorization)
console.log('🌍 Language set:', headerInfo.reqLang)
console.log('📱 App info:', {
console.debug('🔑 Authorization token set:', headerInfo.authorization)
console.debug('🌍 Language set:', headerInfo.reqLang)
console.debug('📱 App info:', {
version: headerInfo.appVersion,
build: headerInfo.buildVersion,
channel: headerInfo.appChannel,

View File

@ -1,7 +1,7 @@
<template>
<div class="host-center gradient-background-circles">
<!-- 顶部导航 -->
<MobileHeader title="Host Center" />
<MobileHeader title="Host Center" :isHomePage="true" />
<!-- 主要内容 -->
<div class="content">
@ -16,7 +16,7 @@
<div class="status-indicator"></div>
<span>已连接</span>
</div>
<div class="user-info">
<div class="avatar">
<span>{{ (userInfo.userNickname || userInfo.name).charAt(0) }}</span>
@ -154,39 +154,83 @@ const identities = [
// APP
const connectToApp = async () => {
console.group('🔗 APP Connection Process')
console.debug('🚀 Starting APP connection...')
if (!isInApp()) {
console.warn('Not running in APP environment')
console.warn('⚠️ Not running in APP environment')
console.debug('🌐 Browser environment detected')
console.debug('📱 APP Bridge objects:')
console.debug(' - window.app:', !!window.app)
console.debug(' - window.webkit:', !!window.webkit)
// APP
appConnected.value = true
console.debug('✅ Skipping APP connection, proceeding with team entry')
await fetchTeamEntry()
console.groupEnd()
return
}
console.debug('📱 APP environment detected')
console.debug('🔍 Checking APP bridge availability:')
console.debug(' - window.app:', !!window.app)
console.debug(' - window.webkit:', !!window.webkit)
connectApplication(async (access) => {
console.log('Received access from APP:', access)
console.debug('📥 Received data from APP:')
console.debug(' - Data type:', typeof access)
console.debug(' - Data length:', access ? access.length : 0)
console.debug(' - Raw data:', access)
const result = parseAccessOrigin(access)
console.debug('🔍 Parsing result:')
console.debug(' - Success:', result.success)
if (result.success) {
console.debug('✅ Access data parsed successfully')
//
headerInfo.value = parseHeader(result.data)
console.debug('📋 Parsed header info:')
console.debug(' - Authorization:', headerInfo.value.authorization ? '✅ Present' : '❌ Missing')
console.debug(' - Language:', headerInfo.value.reqLang)
console.debug(' - App Version:', headerInfo.value.appVersion)
console.debug(' - Build Version:', headerInfo.value.buildVersion)
console.debug(' - System Origin:', headerInfo.value.sysOrigin)
console.debug(' - Device ID:', headerInfo.value.reqImei ? '✅ Present' : '❌ Missing')
// HTTP
console.debug('🔧 Setting HTTP headers...')
setHttpHeaders(headerInfo.value)
//
appConnected.value = true
console.log('APP connection established:', headerInfo.value)
console.debug('🎉 APP connection established successfully')
//
await fetchTeamEntry()
fetchBankBalance()
console.debug('📊 Fetching team entry and bank balance...')
try {
await fetchTeamEntry()
console.debug('✅ Team entry fetched')
fetchBankBalance()
console.debug('✅ Bank balance fetch initiated')
} catch (error) {
console.error('❌ Error in post-connection operations:', error)
}
} else {
console.error('Failed to parse access origin:', result.error)
console.error('❌ Failed to parse access origin:', result.error)
console.debug('🔄 Redirecting to error page...')
//
router.push({ path: '/not_app', query: { message: result.error }})
}
console.groupEnd()
})
console.debug('⏳ Waiting for APP response...')
}
//
@ -258,22 +302,22 @@ const goToNotification = () => {
const fetchTeamEntry = async () => {
try {
const response = await getTeamEntry()
if (response && response.status && response.body) {
userProfile.value = response.body
//
if (response.body.memberProfile) {
userInfo.userNickname = response.body.memberProfile.userNickname
userInfo.account = response.body.memberProfile.account
}
// ID
const userId = response.body.memberProfile?.id
if (userId) {
await checkUserIdentity(userId)
}
return userId
}
} catch (error) {
@ -288,36 +332,36 @@ const checkUserIdentity = async (userId) => {
console.error('用户ID不存在')
return
}
//
if (identityChecked.value) {
console.log('身份已检查,跳过')
console.debug('身份已检查,跳过')
return
}
try {
identityChecked.value = true
const response = await getUserIdentity(userId)
if (response && response.status && response.body) {
const { freightAgent, anchor, agent } = response.body
console.log('用户身份权限:', { freightAgent, anchor, agent })
console.debug('用户身份权限:', { freightAgent, anchor, agent })
// freightAgent > anchor > agent
if (freightAgent) {
console.log('跳转到 coin-seller')
console.debug('跳转到 coin-seller')
router.replace('/coin-seller')
} else if (anchor) {
console.log('跳转到 agency-center')
console.debug('跳转到 agency-center')
router.replace('/agency-center')
} else if (agent) {
// Host
console.log('保持在 host-center')
console.debug('保持在 host-center')
currentIdentity.value = 'host'
} else {
// Host
console.log('无特殊权限,保持在 host-center')
console.debug('无特殊权限,保持在 host-center')
currentIdentity.value = 'host'
}
}
@ -341,7 +385,7 @@ const transfer = () => {
onMounted(async () => {
// APP
await connectToApp()
// APP
if (!isInApp()) {
fetchBankBalance()