Writing · JavaScript · Preact · Web
Chrome's page translation versus your virtual DOM
Why Chrome's page translation makes Preact and React throw "Failed to execute 'insertBefore' on 'Node'", and a narrow DOM patch that fixes it safely.
One morning a crash report from DWEEB said the whole editor had fallen over to its error screen with this:
NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
The top frames were insert and diffChildren, inside the vendor bundle, meaning inside Preact itself. Preact doesn't have bugs like that on ordinary pages. The page wasn't ordinary: the visitor had asked Chrome to translate it.
What browser translation does to your DOM
Chrome's built-in translation (the same machinery as the Google Translate website widget) works on text nodes. For each text node it translates, it inserts a wrapper and moves the original text node inside it:
<!-- Before -->
<button><svg …></svg>Send</button>
<!-- After translation -->
<button><svg …></svg><font><font>Enviar</font></font></button>
That's harmless until your framework touches that part of the tree again. A virtual DOM library keeps references to the real DOM nodes it created. When it needs to insert a new element, it calls parent.insertBefore(newNode, referenceNode) with the sibling it remembers as the reference. But the remembered text node now lives inside a <font>, not inside parent, so the browser throws. Preact guards against a reference that has been detached from the document (!oldDom.parentNode), but not against one that has been moved somewhere else. React has had a long-standing issue about the same class of problem with Google Translate.
In practice it takes a render that inserts an element next to a bare text child. A conditional icon appearing beside a label, or an emoji element appearing mid-paragraph, is enough. A single click and the app is gone.
Reproducing it without a translator
You don't need to drive the translation feature to test this. Wrapping one rendered text node the way the translator does is enough:
function simulateTranslation(element) {
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
const text = walker.nextNode();
const outer = document.createElement("font");
const inner = document.createElement("font");
text.parentNode.insertBefore(outer, text);
outer.appendChild(inner);
inner.appendChild(text); // the original node moves; the framework still holds it
}
Then trigger a render that inserts a sibling before or after that text, and you get the exact error from the report.
The options
- Turn translation off with
translate="no"on the root. That trades a crash for an app the visitor explicitly asked to read in their own language and now can't. They didn't do anything wrong. - Wrap every text node in a span so the framework's references are elements the translator leaves alone. That works, but you have to apply it to every piece of text in the app forever, including text you don't control.
- Make the two DOM methods that throw tolerate a moved node. Preact has no hook around DOM insertion, so this means patching
Node.prototype. It sounds alarming, which is why the rule I set for the patch matters more than the patch itself.
A patch that only acts where the browser would throw
The patch changes behaviour only in the exact situation where the native call would otherwise throw. Every working code path in the app runs exactly as before.
const nativeInsertBefore = Node.prototype.insertBefore;
const nativeRemoveChild = Node.prototype.removeChild;
Node.prototype.insertBefore = function (node, ref) {
if (ref instanceof Node && ref.parentNode !== this) {
// Walk up from the stale reference to the ancestor that IS our child.
// The translator's wrapper stands exactly where the text used to be,
// so inserting before it preserves the intended order.
let anchor = ref;
while (anchor && anchor.parentNode !== this) anchor = anchor.parentNode;
if (anchor) {
reportDesyncOnce(this, ref);
return nativeInsertBefore.call(this, node, anchor);
}
}
return nativeInsertBefore.call(this, node, ref); // throws natively if still invalid
};
Node.prototype.removeChild = function (child) {
if (child instanceof Node && child.parentNode !== this) {
// Not our child any more: someone else moved it. Leave it alone.
reportDesyncOnce(this, child);
return child;
}
return nativeRemoveChild.call(this, child);
};
Some choices are deliberate:
- Insert before the ancestor, not at the end. Appending would be simpler, but it would put the new icon after its label. Walking up to the wrapper keeps the order the app intended.
removeChilddoes nothing for a foreign child. It doesn't go looking for the node and remove it from wherever it lives now. That node belongs to the translator.- Bad arguments still throw. If my code passes something that isn't a node, it still gets the native
TypeError. A real bug of mine must stay loud. - Install it before the first render, and after the crash reporter, because it reports through it.
The cost is measurable but irrelevant: about 100 nanoseconds per insertBefore in a microbenchmark that does nothing else, which disappears next to layout.
Reporting it so a real bug can't hide behind it
A patch that swallows DOM errors could also hide my own mistakes, for example code that moves nodes behind the framework's back. So the guard reports once per page, as a distinct, non-paging event, and the report carries the two facts that tell the cases apart:
- the tag the stale node was found under (
FONTfor Chrome's translator); - any translator markers on the document: Chrome adds the
translated-ltrortranslated-rtlclass to<html>, and Microsoft's translator adds_msttexthashattributes.
A report reading parent=FONT translator=google is a browser rewriting the page, and nothing needs doing. A report with translator=none under an ordinary tag means the guard is covering for a bug of mine, and I go and look.
One deployment detail: the server that receives crash reports had to learn the new event type before the client started sending it. An older server would have treated the unknown type as a crash and paged me for every translated page view.
Takeaway
If your app has visitors who don't read your language, some of them translate it, and your framework's assumptions about owning the DOM will eventually meet a rewritten tree. You can stop them translating, or you can make the two methods that throw tolerate the one situation translation creates, and measure how often it happens. I chose the second. The people who translate the page are trying to use the product.
