You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Popover API跨Shadow边界失效排查:Chrome 118是否支持?

Popover API跨Shadow边界连接失败的问题排查

问题分析

你的实现错误在于在自定义元素的constructor中过早查询外部DOM元素。当constructor执行时,<test-popup>元素还未插入到DOM树中,此时document.querySelector('[popovertarget="testpopup"]')会返回null,无法正确设置popoverTargetElement。

Chrome 118完全支持通过JavaScript API跨Shadow边界连接popover触发器与popover元素,问题不在浏览器版本。

修正后的代码

HTML部分

<test-popup>hello, this is a test</test-popup>
<button popovertarget="testpopup" id="shadow-popover-trigger">this should cross shadow boundaries and trigger a popup</button>

JavaScript部分

const template = document.createElement("template");

template.innerHTML = `
  <div popover id="testpopup">
    <slot></slot>
  </div>
`;

class TestPopup extends HTMLElement {
  constructor() {
    super();
    this._shadowRoot = this.attachShadow({ mode: "open" });
    this._shadowRoot.appendChild(template.content.cloneNode(true));
    this.popover = this._shadowRoot.querySelector("[popover]");
    this.trigger = null;
  }

  connectedCallback() {
    // 元素插入DOM后再查询外部触发器
    this.trigger = document.querySelector('[popovertarget="testpopup"]');
    if (this.trigger) {
      this.trigger.popoverTargetElement = this.popover;
    }
  }

  disconnectedCallback() {
    // 元素移除时清理引用,避免内存泄漏
    if (this.trigger) {
      this.trigger.popoverTargetElement = null;
      this.trigger = null;
    }
  }
}

customElements.define("test-popup", TestPopup);

关键修正点

  • 将查询触发器和设置popoverTargetElement的逻辑移到connectedCallback中,确保元素已插入DOM,外部按钮已存在。
  • 在disconnectedCallback中清理引用,防止内存泄漏。
  • 提前在constructor中获取Shadow DOM内的popover元素,避免重复查询。

内容的提问来源于stack exchange,提问作者Philipp Gfeller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:33:15