Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
In production data monitoring, this crash is often observed. However, when tested under normal circumstances, no issues can be found.
After searching online, I found a clue in a GitHub issue: Google Translate.
The main reason is that when users use Google Translate, some pages will crash and report errors during interactions. On the surface, this seems to be related to abnormal React updates caused by text replacement.
Analysis
After using Google Translate, every piece of text is replaced with a translation wrapped in two layers of <font>
tags.
The
<font>
tag defines the font size, color, and appearance of the content. Technically, it is no longer recommended for use.
<font style="vertical-align: inherit;">
<font style="vertical-align: inherit;">Translation </font>
</font>
Why are there two layers? This is unclear. However, testing shows that manually wrapping text in a single <font>
layer affects the outer <font>
layer, and it also introduces an additional empty <font>
(this occurs if there is text before or after the current <font>
. If there is no other text at the same level, it behaves more normally).
Text1<font data-id="1">Text2</font>
// =>
<font style="vertical-align: inherit;">
<font style="vertical-align: inherit;">Translation1</font>
<font data-id="1">
<font style="vertical-align: inherit;">Translation2</font>
</font>
</font>
<font data-id="1">
<font style="vertical-align: inherit;"></font>
</font>
Crash Analysis
The crash occurs during the concatenation of text variables. If dynamic text is directly concatenated in the React code, the translated page will crash when the text changes.
Solution
Based on the above reasons, the solution is to avoid concatenating dynamic text. Instead, wrap dynamic text with a <span>
tag. It is not necessary to wrap all text; just ensure that when static text and dynamic text are combined, one of them is wrapped in a <span>
.
The <span>
tag can generally replace any other tag.
Special Cases
Sometimes, text concatenation is very obvious in the code, while other times it is less noticeable. For example, content between <></>
can also cause text concatenation, which is harder to detect.