最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Shadow root cannot be created on a host which already hosts a shadow tree - Stack Overflow

programmeradmin2浏览0评论

I'm rendering a react app(Widget) inside Shadow DOM. So I looked at the div id where the widget is getting loaded currently.

See screenshow below.

With this information, I want to create Shadow host like this.


const host = document.querySelector('#widget-_hw');
const shadow = host.attachShadow({ mode: 'open' });
const renderIn = document.createElement('div');

But I'm getting this error.

Failed to execute 'attachShadow' on 'Element': Shadow root cannot be created on a host which already hosts a shadow tree

I'm rendering a react app(Widget) inside Shadow DOM. So I looked at the div id where the widget is getting loaded currently.

See screenshow below.

With this information, I want to create Shadow host like this.


const host = document.querySelector('#widget-_hw');
const shadow = host.attachShadow({ mode: 'open' });
const renderIn = document.createElement('div');

But I'm getting this error.

Failed to execute 'attachShadow' on 'Element': Shadow root cannot be created on a host which already hosts a shadow tree

Share Improve this question edited Feb 28, 2022 at 21:26 Tomaz_ asked Feb 28, 2022 at 20:56 Tomaz_Tomaz_ 4691 gold badge6 silver badges18 bronze badges 4
  • 4 So you are reading the element before it exists. You can not eat your pizza before it is made. – epascarello Commented Feb 28, 2022 at 21:03
  • Your point was correct. I changed the place where I called querySelector so host exist now. But now I'm getting another set of error. – Tomaz_ Commented Feb 28, 2022 at 21:29
  • could you please post the answer if you got it? – johannesMatevosyan Commented Sep 6, 2023 at 15:41
  • It means you have already added the shadow root. You can't add it twice. Check host.shadowRoot is null. If it's null, attach. If it's not null skip. – 1.21 gigawatts Commented Jul 23, 2024 at 16:31
Add a ment  | 

2 Answers 2

Reset to default 1

It's saying you can't attach a shadow document to this element because it already has a document attached.

In your code set a breakpoint and check that it's not getting call twice.

Alternatively, check the shadowRoot property.

const shadow = host.shadowRoot || host.attachShadow({ mode: 'open' });

This one worked for me.

const hostRef = useRef<HTMLDivElement | null>(null);

if (hostRef.current) {
   // const shadowRoot = hostRef.current.attachShadow({ mode: 'open' });
   const shadowRoot = hostRef.current.shadowRoot || hostRef.current.attachShadow({ mode: 'open' });
}
发布评论

评论列表(0)

  1. 暂无评论