From d6525c87e609fd168dc43bb975170a1358762051 Mon Sep 17 00:00:00 2001 From: cyntler Date: Thu, 25 Feb 2021 22:26:06 +0100 Subject: [PATCH] Add hook --- src/index.ts | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/index.ts diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..59eebe5 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,38 @@ +/** + * @name use-window-blur-change-title + * @author cyntler + */ +import { useEffect, useRef } from 'react'; + +const setTitle = (title: string) => { + document.title = title; +}; + +export const useWindowBlurChangeTitle = (titleWhenBlur: string) => { + const previousTitle = useRef(); + + const handleWindowBlur = () => { + previousTitle.current = document.title; + setTitle(titleWhenBlur); + }; + + const handleWindowFocus = () => { + if (previousTitle.current) { + setTitle(previousTitle.current); + } + }; + + useEffect(() => { + if (typeof window === 'undefined') { + return; + } + + window.addEventListener('blur', handleWindowBlur); + window.addEventListener('focus', handleWindowFocus); + + return () => { + window.removeEventListener('blur', handleWindowBlur); + window.removeEventListener('focus', handleWindowFocus); + }; + }, []); +};