Skip to content

Commit

Permalink
Add hook
Browse files Browse the repository at this point in the history
  • Loading branch information
cyntler committed Feb 25, 2021
1 parent f60bfe0 commit d6525c8
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* @name use-window-blur-change-title
* @author cyntler <[email protected]>
*/
import { useEffect, useRef } from 'react';

const setTitle = (title: string) => {
document.title = title;
};

export const useWindowBlurChangeTitle = (titleWhenBlur: string) => {
const previousTitle = useRef<string>();

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);
};
}, []);
};

0 comments on commit d6525c8

Please sign in to comment.