I am detecting popups on a site by overriding window.open with a closure of itself with some additional logic.
const PopupWarning = () => {
const [failedUrl, setFailedUrl] = useState<string | null>(null)
const [showPopupWarning, setShowPopupWarning] = useState<boolean>(false)
window.open = function (open) {
return function (url, name, features) {
name = name || 'default_window_name'
const popup = open.call(window, url, name, features)
try {
popup.focus()
setShowPopupWarning(false)
setFailedUrl(null)
} catch (e) {
setFailedUrl(url.toString())
setShowPopupWarning(true)
}
return popup
}
}(window.open)
...
Is this an acceptable way to do something like this? It works during all of my tests, but I wonder if this code should be in a useCallback or other.
I tried searching for this idea and couldn't find much. I bet overriding window.open is frowned upon, but it's the best solution for this use case (can't change source html). Thanks!
useEffectalso restore the originalwindow.openwhen your component unmounts.window.openat all, just your wrapper function and no monkey patching required but I'm not sure how applicable that is if your pages are mainly static html.