Browse Source

feat: add useCloseServiceOnBack hook to intercept back navigation and trigger Flutter service closure

front-test-2
mortezaei 4 weeks ago
parent
commit
91327051c5
  1. 2
      src/app/questions-list/page.tsx
  2. 41
      src/hooks/use-close-service-on-back.ts

2
src/app/questions-list/page.tsx

@ -30,8 +30,10 @@ import { useI18n } from "@/translations/provider";
import { toFrontendSlug } from "@/data/section-slug-map"; import { toFrontendSlug } from "@/data/section-slug-map";
import SectionsRequest from "./sections-request"; import SectionsRequest from "./sections-request";
import { getStoredAge, getLocalSectionProgress } from "@/components/questions/progress-helper"; import { getStoredAge, getLocalSectionProgress } from "@/components/questions/progress-helper";
import { useCloseServiceOnBack } from "@/hooks/use-close-service-on-back";
export default function QuestionsListPage() { export default function QuestionsListPage() {
useCloseServiceOnBack();
const { dictionary: t, locale } = useI18n(); const { dictionary: t, locale } = useI18n();
const router = useRouter(); const router = useRouter();
const { data: profile } = useMarriageProfileQuery(); const { data: profile } = useMarriageProfileQuery();

41
src/hooks/use-close-service-on-back.ts

@ -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;
Loading…
Cancel
Save