2023-06-10 22:16:02 +02:00
|
|
|
import { useEffect, useState } from "react"
|
|
|
|
|
|
2023-06-07 15:03:27 +02:00
|
|
|
export const useBrowserExtension = () => {
|
2023-06-10 22:16:02 +02:00
|
|
|
const [browserExtensionVersion, setBrowserExtensionVersion] = useState<string>()
|
|
|
|
|
|
|
|
|
|
// the extension will set the "browser-extension-installed" attribute on the root element, monitor it for changes
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
const observer = new MutationObserver(mutations => {
|
|
|
|
|
mutations.forEach(mutation => {
|
|
|
|
|
if (mutation.type === "attributes") {
|
|
|
|
|
const element = mutation.target as Element
|
|
|
|
|
const version = element.getAttribute("browser-extension-installed")
|
|
|
|
|
if (version) setBrowserExtensionVersion(version)
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
observer.observe(document.documentElement, {
|
|
|
|
|
attributes: true,
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return () => observer.disconnect()
|
|
|
|
|
}, [])
|
|
|
|
|
|
|
|
|
|
const isBrowserExtensionInstalled = !!browserExtensionVersion
|
2023-06-07 15:03:27 +02:00
|
|
|
// when not in an iframe, window.parent is a reference to window
|
2023-06-10 22:16:02 +02:00
|
|
|
const isBrowserExtensionPopup = window.parent !== window
|
|
|
|
|
const isBrowserExtensionInstallable = !isBrowserExtensionPopup
|
2023-06-07 15:03:27 +02:00
|
|
|
|
2023-06-10 22:16:02 +02:00
|
|
|
const w = isBrowserExtensionPopup ? window.parent : window
|
|
|
|
|
const openSettingsPage = () => w.postMessage("open-settings-page", "*")
|
|
|
|
|
const openAppInNewTab = () => w.postMessage("open-app-in-new-tab", "*")
|
|
|
|
|
const openLinkInBackgroundTab = (url: string) => w.postMessage(`open-link-in-background-tab:${url}`, "*")
|
2023-06-12 20:54:40 +02:00
|
|
|
const setBadgeUnreadCount = (count: number) => w.postMessage(`set-badge-unread-count:${count}`, "*")
|
2023-06-07 15:03:27 +02:00
|
|
|
|
2023-06-10 22:16:02 +02:00
|
|
|
return {
|
|
|
|
|
browserExtensionVersion,
|
|
|
|
|
isBrowserExtensionInstallable,
|
|
|
|
|
isBrowserExtensionInstalled,
|
|
|
|
|
isBrowserExtensionPopup,
|
|
|
|
|
openSettingsPage,
|
|
|
|
|
openAppInNewTab,
|
|
|
|
|
openLinkInBackgroundTab,
|
2023-06-12 20:54:40 +02:00
|
|
|
setBadgeUnreadCount,
|
2023-06-10 22:16:02 +02:00
|
|
|
}
|
2023-06-07 15:03:27 +02:00
|
|
|
}
|