Method, device, equipment and medium for converting Shadow DOM (Document Object Model) into template label
Breadth-first search and conversion <template> The tag method solves the problem of retrieving nested Shadow DOM content, achieving integrity and style fidelity, and is suitable for various Web Components scenarios.</template>
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-10-23
- Publication Date
- 2026-03-13
AI Technical Summary
Existing technologies struggle to effectively retrieve the content of nested Shadow DOM elements, especially since the content of the Shadow DOM cannot be retrieved within the main frame using element.innerHTML and element.outerHTML, and nested Shadow DOM elements are even more difficult to access.
A breadth-first search is used to traverse the DOM tree, retrieve all Shadow DOM host elements, and convert them into standard DOM nodes by merging adoptedStyleSheets and The content is integrated into the main DOM using tags, preserving style encapsulation logic and pattern information.
It enables comprehensive processing of the entire DOM tree, ensuring content integrity and style fidelity, supports regular DOM API operations, is suitable for various Web Components scenarios, and has strong compatibility.
Smart Images

Figure CN121658121A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to a method, apparatus, device, and medium for converting a Shadow DOM into template tags. Background Technology
[0002] Shadow DOM is a crucial component of Web Components technology. Its core function is to encapsulate the DOM tree, thereby isolating the DOM structure and styles within a component from the external code. It attaches a hidden and independent DOM subtree to the regular DOM tree. The styles and behaviors of this subtree neither affect nor are affected by the styles and behaviors of the external elements. Specifically, Shadow DOM creates a "shadow" root node (Shadow Root) and attaches the shadow tree to the regular DOM element (i.e., the shadow host), thus forming a boundary (ShadowBoundary) and achieving strong encapsulation.
[0003] However, the existing technology has some drawbacks: first, the content of the Shadow DOM cannot be obtained through element.innerHTML and element.outerHTML in the main frame; second, it is even more difficult to obtain the content of nested Shadow DOMs. Summary of the Invention
[0004] The technical problem to be solved by the present invention is to provide a method, apparatus, device and medium for converting Shadow DOM into template tags, so as to facilitate users to quickly obtain all the content of Shadow DOM.
[0005] In a first aspect, the present invention provides a method for converting a Shadow DOM into template tags, comprising the following steps: Step S1: Traverse and obtain all Shadow DOM host elements; Step S2: Convert a single Shadow DOM host into a standard DOM node; Step S3: Update the transformed standard DOM nodes to the main DOM.
[0006] Secondly, the present invention provides a device for converting a Shadow DOM into template tags, comprising: Iterate through the module to retrieve all Shadow DOM host elements; The Transform Node module converts a single Shadow DOM host into a standard DOM node; The update node module updates the main DOM with the transformed standard DOM nodes.
[0007] Thirdly, the present invention provides an electronic device including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the method described in the first aspect.
[0008] Fourthly, the present invention provides a computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the method described in the first aspect.
[0009] One or more technical solutions provided by this invention have at least the following technical effects or advantages: 1. Completeness: Breadth-first search can recursively retrieve all nested Shadow DOMs, avoiding omission of deep-level encapsulated content and ensuring comprehensive processing of the entire DOM tree (including all Shadow DOM subtrees).
[0010] 2. Compatibility: Convert the Shadow DOM to one with the `shadowrootmode` property. <template>The tag conforms to the HTML standard format and can be correctly parsed by mainstream browsers. At the same time, it retains the original Shadow Root mode (open / closed) information and maintains the core metadata of the encapsulation feature.
[0011] 3. Operability: The converted content is integrated into the main DOM in the form of standard DOM nodes, which solves the problem that innerHTML / outerHTML cannot directly obtain the Shadow DOM content, making it easier to perform subsequent operations such as querying, modifying, and serializing through the regular DOM API.
[0012] 4. Style fidelity: By merging adoptedStyleSheets and <style>标签样式,在转换过程中保留原Shadow DOM的样式封装逻辑,避免样式丢失或冲突,确保转换后节点的视觉表现与原Shadow DOM一致。
[0013] 5、通用性:流程清晰且基于Web标准API(如shadowRoot、adoptedStyleSheets、shadowrootmode),不依赖特定框架,适用于各种使用Shadow DOM的Web Components场景。
[0014] 上述说明仅是本发明技术方案的概述,为了能够更清楚了解本发明的技术手段,而可依照说明书的内容予以实施,并且为了让本发明的上述和其它目的、特征和优点能够更明显易懂,以下特举本发明的具体实施方式。附图说明
[0015] 下面参照附图结合实施例对本发明作进一步的说明。
[0016] 图1为本发明实施例一中方法中的流程图;图2为本发明实施例二中装置的结构示意图。具体实施方式
[0017] 本申请实施例中的技术方案,总体思路如下:步骤1、构造一个方法:获取所有的Shadow DOM,包括嵌套的Shadow DOM;步骤2、构造一个方法:将Shadow DOM转换为普通标准的DOM节点;步骤3、将转换后的节点更新到主DOM上。
[0018] 具体实现如下:将Shadow DOM转换为标准的DOM节点,这样可以很方便在主DOM上做操作1:构造一个方法:获取所有的Shadow DOM,包括嵌套的Shadow DOM / / 获取所有shadowHost(使用广度优先搜索)function findAllShadowHosts(base = document) {const shadowHosts = [];const queue = [base];while (queue.length > 0) {const currentNode = queue.shift(); / / 检查当前节点是否有shadowRootif (currentNode.shadowRoot) {shadowHosts.push(currentNode); / / 将shadowRoot也添加到队列中以搜索其内部queue.push(currentNode.shadowRoot);} / / 将当前节点的所有子元素添加到队列let child = currentNode.firstElementChild;while (child) {queue.push(child);child = child.nextElementSibling;}}return shadowHosts;}2: 构造一个方法:将 Shadow DOM 转换为普通标准的DOM 节点function convertShadowDOMToTemplate(shadowHost, includeStyles = true){ / / includeStyles: 是否要包含 Shadow DOM 的样式if (!shadowHost || !shadowHost.shadowRoot) {console.warn('Element does not have a shadow root');return '';}const shadowRoot = shadowHost.shadowRoot;const mode = shadowRoot.mode || 'open'; / / 获取 shadow root 的内容let shadowContent = shadowRoot.innerHTML; / / 处理样式if (includeStyles) {const styles = []; / / 获取 adoptedStyleSheets 中的样式if (shadowRoot.adoptedStyleSheets && shadowRoot.adoptedStyleSheets.length > 0) {shadowRoot.adoptedStyleSheets.forEach(sheet => {const rules = sheet.cssRules || sheet.rules;if (rules) {for (let i = 0; i < rules.length; i++) {styles.push(rules[i].cssText);}}});} / / 获取 <style> 标签中的样式const styleElements = shadowRoot.querySelectorAll('style');styleElements.forEach(styleEl => {if (styleEl.textContent) {styles.push(styleEl.textContent);}}); / / 如果有样式,添加到内容前面if (styles.length > 0) {const styleContent = styles.join('\n');shadowContent = `<style>${styleContent}< / style> ${shadowContent}`; } } / / Create template tag const template = ` <template shadowrootmode="${mode}">${shadowContent}< / template> `; return template; } 3. Update the transformed nodes to the main DOM. const template = convertShadowDOMToTemplate(shadowHost, includeStyles); / / Converts the Shadow DOM into a template node. if (template) { clonedHost.innerHTML = template + clonedHost.innerHTML; / / Update shadow host content } Example
[0019] like Figure 1 As shown, this embodiment provides a method for converting the Shadow DOM into template tags, including the following steps: Step S1: Traverse and obtain all Shadow DOM host elements; Step S2: Convert a single Shadow DOM host into a standard DOM node; Step S3: Update the transformed standard DOM nodes to the main DOM.
[0020] In this embodiment, preferably, step S1 specifically involves: traversing the entire DOM tree using a breadth-first search method; if a node contains a Shadow Root, then marking the node as a Shadow DOM host and recording it; and continuing to search for nodes inside the Shadow Root until all DOM nodes have been traversed and all Shadow DOM hosts have been collected.
[0021] In this embodiment, preferably, step S2 specifically involves: for each Shadow DOM host, extracting the content of its Shadow Root; if styles need to be preserved, merging the style rules introduced by adoptedStyleSheets and the style content of the internal style tag in Shadow Root, and placing the merged style before the Shadow Root content; finally, encapsulating the processed content into a template tag with the shadowrootmode attribute to form a standard DOM node form.
[0022] In this embodiment, preferably, step S3 specifically involves: for each collected Shadow DOM host, using the transformation result of step S2, placing the transformed template tag in the DOM structure of the host element, thereby integrating the Shadow DOM content into the main DOM tree in a standard form to complete the update.
[0023] Based on the same inventive concept, this application also provides an apparatus corresponding to the method in Embodiment 1, as detailed in Embodiment 2. Example
[0024] like Figure 2 As shown, this embodiment provides a device for converting the Shadow DOM into template tags, including: Iterate through the module to retrieve all Shadow DOM host elements; The Transform Node module converts a single Shadow DOM host into a standard DOM node; The update node module updates the main DOM with the transformed standard DOM nodes.
[0025] In this embodiment, preferably, the traversal acquisition module specifically performs the following steps: traversing the entire DOM tree using a breadth-first search method; if a node contains a Shadow Root, then marking the node as a Shadow DOM host and recording it; simultaneously continuing to search for nodes inside the Shadow Root until all DOM nodes have been traversed and all Shadow DOM hosts have been collected.
[0026] In this embodiment, preferably, the transformation node module specifically performs the following steps: for each Shadow DOM host, extract the content of its Shadow Root; if styles need to be preserved, merge the style rules introduced by adoptedStyleSheets and the style content of the internal style tag in Shadow Root, and place the merged style before the Shadow Root content; finally, encapsulate the processed content into a template tag with the shadowrootmode attribute to form a standard DOM node form.
[0027] In this embodiment, preferably, the update node module specifically performs the following: for each collected Shadow DOM host, the transformation result of the transformation node module is used to place the transformed template tag in the DOM structure of the host element, thereby integrating the Shadow DOM content into the main DOM tree in a standard form and completing the update.
[0028] Since the apparatus described in Embodiment 2 of the present invention is an apparatus used to implement the method of Embodiment 1 of the present invention, those skilled in the art can understand the specific structure and variations of the apparatus based on the method described in Embodiment 1 of the present invention, and therefore will not be described again here. All apparatuses used in the method of Embodiment 1 of the present invention fall within the scope of protection of the present invention.
[0029] Based on the same inventive concept, this application provides an electronic device embodiment corresponding to Embodiment 1, as detailed in Embodiment 3. Example
[0030] This embodiment provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor. When the processor executes the computer program, it can implement any of the implementation methods in Embodiment 1.
[0031] Since the electronic device described in this embodiment is the device used to implement the method in Embodiment 1 of this application, those skilled in the art can understand the specific implementation method and various variations of the electronic device in this embodiment based on the method described in Embodiment 1 of this application. Therefore, how the electronic device implements the method in the embodiment of this application will not be described in detail here. Any device used by those skilled in the art to implement the method in the embodiment of this application falls within the scope of protection of this application.
[0032] Based on the same inventive concept, this application provides a storage medium corresponding to Embodiment 1, as detailed in Embodiment 4. Example
[0033] This embodiment provides a computer-readable storage medium storing a computer program thereon. When the computer program is executed by a processor, it can implement any of the implementation methods in Embodiment 1.
[0034] Those skilled in the art will understand that embodiments of the present invention can be provided as methods, systems, or computer program products. Therefore, the present invention can take the form of a completely hardware embodiment, a completely software embodiment, or an embodiment combining software and hardware aspects. Furthermore, the present invention can take the form of a computer program product embodied on one or more computer-usable storage media (including, but not limited to, disk storage, CD-ROM, optical storage, etc.) containing computer-usable program code.
[0035] This invention is described with reference to flowchart illustrations and / or block diagrams of methods, apparatus (systems), and computer program products according to embodiments of the invention. It will be understood that each block of the flowchart illustrations and / or block diagrams, and combinations of blocks in the flowchart illustrations and / or block diagrams, can be implemented by computer program instructions. These computer program instructions can be provided to a processor of a general-purpose computer, special-purpose computer, embedded processor, or other programmable data processing apparatus to produce a machine, such that the instructions, which execute via the processor of the computer or other programmable data processing apparatus, generate instructions for implementing the flowchart illustrations and / or block diagrams. Figure 1 One or more processes and / or boxes Figure 1 A device that provides the functions specified in one or more boxes.
[0036] These computer program instructions may also be stored in a computer-readable storage medium that can direct a computer or other programmable data processing device to function in a particular manner, such that the instructions stored in the computer-readable storage medium produce an article of manufacture including instruction means, which are implemented in a process Figure 1 One or more processes and / or boxes Figure 1 The function specified in one or more boxes.
[0037] These computer program instructions may also be loaded onto a computer or other programmable data processing equipment to cause a series of operational steps to be performed on the computer or other programmable equipment to produce a computer-implemented process, thereby providing instructions that execute on the computer or other programmable equipment for implementing the process. Figure 1 One or more processes and / or boxes Figure 1 The steps of the function specified in one or more boxes.
[0038] While specific embodiments of the present invention have been described above, those skilled in the art should understand that the specific embodiments described are merely illustrative and not intended to limit the scope of the present invention. Equivalent modifications and variations made by those skilled in the art in accordance with the spirit of the present invention should be covered within the scope of protection of the claims of the present invention.< / template>
Claims
1. A method for converting the Shadow DOM into template tags, characterized in that: Includes the following steps: Step S1: Traverse and obtain all Shadow DOM host elements; Step S2: Convert a single Shadow DOM host into a standard DOM node; Step S3: Update the transformed standard DOM nodes to the main DOM.
2. The method for converting Shadow DOM into template tags according to claim 1, characterized in that: Step S1 specifically involves: traversing the entire DOM tree using a breadth-first search approach; if a node contains a Shadow Root, marking the node as a Shadow DOM host and recording it; and continuing to search for nodes inside the Shadow Root until all DOM nodes have been traversed and all Shadow DOM hosts have been collected.
3. A method for converting a Shadow DOM into template tags according to claim 1, characterized in that: Step S2 specifically involves: for each Shadow DOM host, extracting the content of its Shadow Root; if styles need to be preserved, merging the style rules introduced by adoptedStyleSheets and the style content of the internal style tag in Shadow Root, and placing the merged style before the Shadow Root content; finally, encapsulating the processed content into a template tag with the shadowrootmode attribute to form a standard DOM node form.
4. A method for converting a Shadow DOM into template tags according to claim 3, characterized in that: Step S3 specifically involves: for each collected Shadow DOM host, using the transformation result of step S2, placing the transformed template tag in the DOM structure of the host element, thereby integrating the Shadow DOM content into the main DOM tree in a standard form and completing the update.
5. A device for converting a Shadow DOM into template tags, characterized in that: include: Iterate through the module to retrieve all Shadow DOM host elements; The Transform Node module converts a single Shadow DOM host into a standard DOM node; The update node module updates the main DOM with the transformed standard DOM nodes.
6. A device for converting a Shadow DOM into template tags according to claim 5, characterized in that: The traversal acquisition module specifically works as follows: it traverses the entire DOM tree using a breadth-first search method. If a node contains a Shadow Root, it marks the node as a Shadow DOM host and records it. At the same time, it continues to search for nodes inside the Shadow Root until all DOM nodes have been traversed and all Shadow DOM hosts have been collected.
7. A device for converting a Shadow DOM into template tags according to claim 5, characterized in that: The transformation node module specifically works as follows: for each Shadow DOM host, extract the content of its Shadow Root; if styles need to be preserved, merge the style rules imported through adoptedStyleSheets and the style content of the internal style tag in Shadow Root, and place the merged style before the Shadow Root content; finally, encapsulate the processed content into a template tag with the shadowrootmode attribute to form a standard DOM node form.
8. A device for converting a Shadow DOM into template tags according to claim 5, characterized in that: The update node module specifically works as follows: for each collected Shadow DOM host, the transformation result of the transformation node module is used to place the transformed template tag in the DOM structure of the host element, thereby integrating the Shadow DOM content into the main DOM tree in a standard form and completing the update.
9. An electronic device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes the program, it implements the method as described in any one of claims 1 to 4.
10. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the program is executed by the processor, it implements the method as described in any one of claims 1 to 4.