only request notification permissions on the notifications page

This commit is contained in:
keyan 2023-06-01 14:41:20 -05:00
parent f4b81b0ff0
commit c4b96b998f
2 changed files with 6 additions and 5 deletions

View File

@ -72,7 +72,7 @@ export default function Header ({ sub }) {
onCompleted: (data) => { onCompleted: (data) => {
const notified = JSON.parse(localStorage.getItem('notified')) || false const notified = JSON.parse(localStorage.getItem('notified')) || false
if (!notified && data.hasNewNotes) { if (!notified && data.hasNewNotes) {
notification.show('you have new notifications') notification.show('you have Stacker News notifications')
} }
localStorage.setItem('notified', data.hasNewNotes) localStorage.setItem('notified', data.hasNewNotes)
} }

View File

@ -301,10 +301,11 @@ export const NotificationProvider = ({ children }) => {
const [isDefaultPermission, setIsDefaultPermission] = useState(isSupported ? window.Notification.permission === 'default' : undefined) const [isDefaultPermission, setIsDefaultPermission] = useState(isSupported ? window.Notification.permission === 'default' : undefined)
const [isGranted, setIsGranted] = useState(isSupported ? window.Notification.permission === 'granted' : undefined) const [isGranted, setIsGranted] = useState(isSupported ? window.Notification.permission === 'granted' : undefined)
const me = useMe() const me = useMe()
const router = useRouter()
const show_ = (title, options) => { const show_ = (title, options) => {
const icon = '/android-chrome-24x24.png' const icon = '/android-chrome-24x24.png'
window.Notification(title, { icon, ...options }) return new window.Notification(title, { icon, ...options })
} }
const show = useCallback((...args) => { const show = useCallback((...args) => {
@ -317,15 +318,15 @@ export const NotificationProvider = ({ children }) => {
setIsDefaultPermission(window.Notification.permission === 'default') setIsDefaultPermission(window.Notification.permission === 'default')
if (result === 'granted') { if (result === 'granted') {
setIsGranted(result === 'granted') setIsGranted(result === 'granted')
show_('you have enabled notifications') show_('Stacker News notifications enabled')
} }
}) })
}, [isDefaultPermission]) }, [isDefaultPermission])
useEffect(() => { useEffect(() => {
if (!me || !isSupported || !isDefaultPermission) return if (!me || !isSupported || !isDefaultPermission || router.pathname !== '/notifications') return
requestPermission() requestPermission()
}, []) }, [router?.pathname])
const ctx = { isBrowser, isSupported, isDefaultPermission, isGranted, show } const ctx = { isBrowser, isSupported, isDefaultPermission, isGranted, show }