mirror of
https://github.com/Athou/commafeed.git
synced 2026-03-21 21:37:29 +00:00
use browser extension to open tab in background (#1074)
This commit is contained in:
@@ -1,9 +1,44 @@
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
export const useBrowserExtension = () => {
|
||||
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
|
||||
// when not in an iframe, window.parent is a reference to window
|
||||
const isBrowserExtension = window.parent !== window
|
||||
const isBrowserExtensionPopup = window.parent !== window
|
||||
const isBrowserExtensionInstallable = !isBrowserExtensionPopup
|
||||
|
||||
const openSettingsPage = () => window.parent.postMessage("open-settings-page", "*")
|
||||
const openAppInNewTab = () => window.parent.postMessage("open-app-in-new-tab", "*")
|
||||
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}`, "*")
|
||||
|
||||
return { isBrowserExtension, openSettingsPage, openAppInNewTab }
|
||||
return {
|
||||
browserExtensionVersion,
|
||||
isBrowserExtensionInstallable,
|
||||
isBrowserExtensionInstalled,
|
||||
isBrowserExtensionPopup,
|
||||
openSettingsPage,
|
||||
openAppInNewTab,
|
||||
openLinkInBackgroundTab,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user