Repository navigation
fix(core): 被接管的 script/link 以注释节点为锚点提供 parentNode、remove、contains - #1121
Merged
Merged
Conversation
- 被接管元素的 parentNode/parentElement 指向插入时的 head/body,注释节点移除后为 null - removeChild/remove 移除注释节点,script 同时移除 js iframe 中的脚本 - head/body 的 contains 以注释节点判断,body 补充 removeChild/contains 重写 - 删除样式 link 暂不移除对应 style,保持现有行为 Co-authored-by: Cursor <cursoragent@cursor.com>
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
背景
wujie 接管子应用动态插入的
<script>和样式<link>:脚本放到 js iframe 中执行,样式转成<style>,原位置只留一个注释节点,原元素始终游离。因此:n.parentNodenulln.parentNode.removeChild(n)n.remove()document.body.contains(n)truefalse不判空直接调用
parentNode.removeChild是加载 SDK 时常见的写法。#1053 当时用伪造的parentNode规避报错,但伪造对象永远不为空、只提供空操作的removeChild,所以没有合入。修改
以接管时已有的注释节点为锚点表示元素的逻辑位置,不额外维护其他状态:
parentNode/parentElement:有真实父节点时返回真实父节点,否则返回注释节点的父节点。注释节点被移除(包括容器被外部清空)后返回null。head/body.removeChild:被移除元素的注释节点在当前容器中时,删除注释节点;script 继续沿用原有逻辑,移除 js iframe 中对应的脚本。注释节点不在当前容器中时打 warn,并按原有逻辑处理。remove():没有真实父节点时,转给逻辑父节点的removeChild。contains:被接管的元素以注释节点是否在容器中来判断。removeChild/contains重写,与 head 保持一致。body 的removeChild取原型链上的方法,保留 iframe 中原有的容错补丁(fix: 修复通过appendChild添加的外部脚本中使用document.body.removeChild移除脚本报错阻塞代码执行的问题 #839)。已知限制与行为变化
<style>,样式保持不变,和修复前一样。完整支持需要处理共享样式、加载中被移除、href 尚未设置等情况,有需求时单独处理。script.parentNode判断「是否已插入」的代码,结果会从null变为 head/body,和原生一致。验证
__test__/unit/hijacked-element-parent.test.ts(8 个用例)。parentNode === body、contains为 true;parentNode.removeChild不抛错,js iframe 中的脚本被移除,之后parentNode为null。remove()后,js iframe 中的脚本被移除。parentNode === head;parentNode.removeChild不抛错,之后parentNode为null、contains为 false。document.body.removeChild(n)仍然正常,且不再打 warn。Related: #1053, #524