@@ -44,15 +44,11 @@ if (Capacitor.isNativePlatform()) {
4444 // Note sure it's doing anything, though. Need to check
4545 StatusBar . setOverlaysWebView ( { overlay : false } ) . catch ( console . warn )
4646
47- App . addListener ( 'backButton' , ( { canGoBack} ) => {
48- // Only navigate back when the WebView actually has history to pop;
49- // otherwise exit the app so the back button doesn't become a dead no-op
50- // at the root of the stack.
51- if ( canGoBack ) {
52- window . dispatchEvent ( new CustomEvent ( 'appBackButton' ) )
53- } else {
54- App . exitApp ( )
55- }
47+ // NOTE: don't use the event's `canGoBack` — it reflects the native WebView's
48+ // history (webView.canGoBack()), which stays false because we navigate via
49+ // history.pushState inside a single document. The handler decides instead.
50+ App . addListener ( 'backButton' , ( ) => {
51+ window . dispatchEvent ( new CustomEvent ( 'appBackButton' ) )
5652 } )
5753
5854 // Remove live update as the free plan is very limited (100 live updates per year). Do releases on Play Store instead.
@@ -100,6 +96,24 @@ function printBuildInfo() {
10096 }
10197}
10298
99+ const navigationHistory : string [ ] = [ ]
100+
101+ function useTrackedHistory ( ) {
102+ // asPath includes the query string, so back restores the previous page
103+ // *with* its filters/search state (unlike usePathname, which drops it).
104+ const { asPath} = useRouter ( )
105+ useEffect ( ( ) => {
106+ if ( ! asPath ) return
107+ navigationHistory . push ( asPath )
108+ } , [ asPath ] )
109+ return navigationHistory
110+ }
111+
112+ function updateHistoryBack ( ) {
113+ navigationHistory . pop ( )
114+ navigationHistory . pop ( )
115+ }
116+
103117// specially treated props that may be present in the server/static props
104118type PageProps = { auth ?: AuthUser }
105119
@@ -151,9 +165,22 @@ function MyApp(props: AppProps<PageProps>) {
151165 }
152166 } , [ ] )
153167
168+ useTrackedHistory ( )
154169 useEffect ( ( ) => {
170+ // All this is to handle the back button on mobile when returning to the startup page
171+ // (router.back() does not go back to the startup / home page)
155172 const handleBack = ( ) => {
156- router . back ( )
173+ debug ( 'handleBack:' , navigationHistory )
174+ if ( navigationHistory . length > 2 ) {
175+ updateHistoryBack ( )
176+ router . back ( )
177+ } else if ( navigationHistory . length === 2 ) {
178+ const path = navigationHistory [ 0 ]
179+ updateHistoryBack ( )
180+ router . push ( path )
181+ } else if ( Capacitor . isNativePlatform ( ) ) {
182+ App . minimizeApp ( )
183+ }
157184 }
158185
159186 window . addEventListener ( 'appBackButton' , handleBack )
0 commit comments