Tips / Disabling browser translation

Disabling browser translation

How to prevent browser translation features from interfering with contenteditable editing

Difficulty: Beginner
Category: browser-feature
browser-translationgoogle-translatedom-manipulationprevention

Problem

When Google Translate or other browser translation features are activated, they manipulate the DOM and break contenteditable functionality.

Solution

1. Use translate=β€œno” Attribute

Add attribute to disable translation on contenteditable elements.

<div contenteditable="true" translate="no">
  Editable content that should not be translated
</div>

2. Use notranslate Class

Google Translate respects this class.

<div contenteditable="true" class="notranslate">
  Editable content
</div>

3. Reapply Attributes with MutationObserver

Reapply contenteditable attributes after translation.

const observer = new MutationObserver((mutations) => {
  for (const mutation of mutations) {
    if (mutation.type === 'attributes' && 
        mutation.attributeName === 'contenteditable') {
      // Reapply contenteditable if removed
      if (!mutation.target.hasAttribute('contenteditable')) {
        mutation.target.setAttribute('contenteditable', 'true');
      }
    }
  }
});

observer.observe(editableElement, {
  attributes: true,
  attributeFilter: ['contenteditable']
});

4. Disable Translation During Editing

Detect editing mode and disable translation.

let isEditing = false;

editableElement.addEventListener('focus', () => {
  isEditing = true;
  document.documentElement.setAttribute('translate', 'no');
});

editableElement.addEventListener('blur', () => {
  isEditing = false;
  document.documentElement.removeAttribute('translate');
});

Notes

  • Not all translation tools respect attributes
  • MutationObserver may have performance overhead
  • Consider user experience when disabling translation
Edit on GitHub