Created
August 12, 2025 09:51
-
-
Save librz/bcfedfe3ea847d52fc5d408d8b472b67 to your computer and use it in GitHub Desktop.
A failed attampt to controlling windows using React refs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// why this won't work: | |
// 1. ref is scoped to component | |
// 2. there's no way to know whether the window is already opened | |
import { useMemo, useRef } from "react"; | |
export type WindowConfig = { | |
/** window path */ | |
path: string; | |
/** window name */ | |
name: string; | |
/** | |
* window features (used to open window) | |
* @link https://developer.mozilla.org/en-US/docs/Web/API/Window/open#windowfeatures | |
*/ | |
features?: string; | |
}; | |
export function useWindowControl(windowConfig: WindowConfig) { | |
const windowRef = useRef<Window | null>(); | |
const { closeWindow, openWindow, toggleWindow } = useMemo(() => { | |
function openWindow() { | |
if (windowRef.current && !windowRef.current.closed) { | |
windowRef.current.focus(); | |
return; | |
} | |
const { path, name, features } = windowConfig; | |
windowRef.current = window.open(path, name, features); | |
if (!windowRef.current) { | |
// eslint-disable-next-line no-console | |
console.error("Popup blocked. Please allow popups for this website."); | |
} | |
} | |
function closeWindow() { | |
if (!windowRef.current) { | |
return; | |
} | |
windowRef.current.close(); | |
windowRef.current = null; // Reset the ref | |
} | |
function toggleWindow() { | |
if (!windowRef.current || windowRef.current.closed) { | |
openWindow(); | |
} else { | |
closeWindow(); | |
} | |
} | |
return { closeWindow, openWindow, toggleWindow }; | |
}, [windowConfig]); | |
return { windowRef, openWindow, closeWindow, toggleWindow }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment