()
| 20 | |
| 21 | // content环境的特殊初始化 |
| 22 | contentInit() { |
| 23 | this.server.on("runtime/addElement", (data: { params: [number | null, string, Record<string, any> | null] }) => { |
| 24 | const [parentNodeId, tagName, tmpAttr] = data.params; |
| 25 | |
| 26 | const msg = this.msg as CustomEventMessage; |
| 27 | |
| 28 | // 取回 parentNode(如果存在) |
| 29 | let parentNode: Node | undefined; |
| 30 | if (parentNodeId) { |
| 31 | parentNode = msg.getAndDelRelatedTarget(parentNodeId) as Node | undefined; |
| 32 | } |
| 33 | |
| 34 | // 创建元素并设置属性 |
| 35 | const el = <Element>document.createElement(tagName); |
| 36 | const attr = tmpAttr ? { ...tmpAttr } : {}; |
| 37 | let textContent = ""; |
| 38 | if (attr.textContent) { |
| 39 | textContent = attr.textContent; |
| 40 | delete attr.textContent; |
| 41 | } |
| 42 | for (const key of Object.keys(attr)) { |
| 43 | el.setAttribute(key, attr[key]); |
| 44 | } |
| 45 | if (textContent) el.textContent = textContent; |
| 46 | |
| 47 | // 优先挂到 parentNode,否则挂到 head/body/任意节点 |
| 48 | const node = parentNode || document.head || document.body || document.querySelector("*"); |
| 49 | node.appendChild(el); |
| 50 | |
| 51 | // 返回节点引用 id,供另一侧再取回 |
| 52 | const nodeId = msg.sendRelatedTarget(el); |
| 53 | return nodeId; |
| 54 | }); |
| 55 | } |
| 56 | |
| 57 | init() { |
| 58 | this.server.on("runtime/emitEvent", (data: EmitEventRequest) => { |
no test coverage detected