Detecting Google Chrome Translation

前端 未结 4 2189
难免孤独
难免孤独 2020-12-15 20:39

I\'ve added the Google Translation Bar to our website but due to how the layout works if the translation on the main navigation is longer than English is pushes some links d

4条回答
  •  庸人自扰
    2020-12-15 20:59

    As of 2019 the selected answer above doesn't seem to entirely work, however I have been able to use the following modified version to track the class name changes to the element (document.documentElement) when translate or "Show Original" is used:

    var observer = new MutationObserver(function (event) {
        if(document.documentElement.className.match('translated')) {
            alert("Page translate");
        } else {
            alert("Page untranslate");
        }
    });
    
    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['class'],
      childList: false,
      characterData: false
    });
    

    However it's important to note that this will trigger at the beginning of page translation, before the individual content has actually been changed.

    If you need to perform an action which depends on the characteristics of the translated text (e.g. to check if it now overflows a div), then you would need to track changes on elements with text content to see if they have actually been translated, while also using the above code to set a flag to determine whether the change is a result of a translation, or a reversion to the original text.

提交回复
热议问题