Last active
November 25, 2024 19:29
-
-
Save javascripter/1e9cb72bedb8e3b2273e268dd3b17241 to your computer and use it in GitHub Desktop.
Detection of Google Translate Usage in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react' | |
export function useIsMachineTranslationEnabled() { | |
const [isMachineTranslationEnabled, setIsMachineTranslationEnabled] = | |
React.useState(false) | |
React.useEffect(() => { | |
if (isMachineTranslationEnabled) { | |
return | |
} | |
const originalLang = document.documentElement.lang | |
// For most browsers including Chrome, Firefox, and Safari. | |
const documentElementObserver = new MutationObserver(() => { | |
const lang = document.documentElement.lang | |
if (lang !== originalLang) { | |
setIsMachineTranslationEnabled(true) | |
} | |
}) | |
documentElementObserver.observe(document.documentElement, { | |
attributes: true, | |
attributeFilter: ['lang'], | |
childList: false, | |
characterData: false, | |
}) | |
// For Microsoft Edge | |
let titleObserver: MutationObserver | null = null | |
const title = document.querySelector('title') | |
if (title != null) { | |
titleObserver = new MutationObserver(() => { | |
if (title.hasAttribute('_msttexthash')) { | |
setIsMachineTranslationEnabled(true) | |
} | |
}) | |
titleObserver.observe(title, { | |
attributes: true, | |
attributeFilter: ['_msttexthash'], | |
childList: false, | |
characterData: false, | |
}) | |
} | |
return () => { | |
documentElementObserver.disconnect() | |
titleObserver?.disconnect() | |
} | |
}, [isMachineTranslationEnabled]) | |
return isMachineTranslationEnabled | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment