|
|
@ -0,0 +1,41 @@ |
|
|
|
|
|
"use client"; |
|
|
|
|
|
|
|
|
|
|
|
import { useEffect } from "react"; |
|
|
|
|
|
|
|
|
|
|
|
/** |
|
|
|
|
|
* Hook to intercept browser/hardware back button (popstate) and trigger |
|
|
|
|
|
* Flutter's `close_service` action when running inside Flutter WebView. |
|
|
|
|
|
*/ |
|
|
|
|
|
export function useCloseServiceOnBack(enabled: boolean = true) { |
|
|
|
|
|
useEffect(() => { |
|
|
|
|
|
if (!enabled || typeof window === "undefined") { |
|
|
|
|
|
return; |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
const app = (window as any).HabibApp; |
|
|
|
|
|
if (!app?.postMessage) { |
|
|
|
|
|
return; |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
// Push a dummy history state so hardware back triggers popstate instead of navigating away
|
|
|
|
|
|
window.history.pushState({ closeOnBack: true }, "", window.location.href); |
|
|
|
|
|
|
|
|
|
|
|
const handlePopState = () => { |
|
|
|
|
|
if ((window as any).HabibApp?.postMessage) { |
|
|
|
|
|
// Keep the state pinned in webview and notify Flutter to close the webview
|
|
|
|
|
|
window.history.pushState({ closeOnBack: true }, "", window.location.href); |
|
|
|
|
|
(window as any).HabibApp.postMessage( |
|
|
|
|
|
JSON.stringify({ action: "close_service" }), |
|
|
|
|
|
); |
|
|
|
|
|
} |
|
|
|
|
|
}; |
|
|
|
|
|
|
|
|
|
|
|
window.addEventListener("popstate", handlePopState); |
|
|
|
|
|
|
|
|
|
|
|
return () => { |
|
|
|
|
|
window.removeEventListener("popstate", handlePopState); |
|
|
|
|
|
}; |
|
|
|
|
|
}, [enabled]); |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
export default useCloseServiceOnBack; |