I have a rich editor I'm re-writing as a lit-element custom element. I'm using Firefox (latest) for testing. I'm trying to get the selection for the content editable element in the custom element's shadowDom (in a method).
In the Firefox debugger), this.shadowRoot
looks correct for the shadowRoot element, but this.shadowRoot.getSelection
is not defined,
even though DocumentOrShadowRoot
says shadowRoot.getSelection()
is the proper way to get the selection within the shadow DOM.
Can anybody shed light on something I'm missing?
Many thanks!
I tried to get a Selection within shadowdom myself for days. My understanding so far is that "this.shadowRoot.getSelection()" works fine (tested in Chrome and Firefox), but only for shadowdom in "open"-mode, because "this.shadowRoot" can't be accessed in "closed"-mode: "Cannot read property 'getSelection' of null".
Of course you can store a reference to shadowRoot yourself at initialization time, however it is hard to keep this reference private in JavaScript.
There's a proposal currently in development to extend the Selection API to properly handle Shadow DOM. See https://twitter.com/bocoup/status/1459120675390689284?s=20
As far as I can tell, this is the current state of affairs in Dec 2021:
ShadowRoot.getSelection
is a non-standard API.
On Chromium, calling document.getSelection
will not pierce into the Shadow DOM and gives you some unhelpful high-level element. But it does expose the non-standard getSelection
method on the ShadowRoot.
On Firefox, it does not implement ShadowRoot.getSelection
, but document.getSelection
will pierce through shadow dom and give you the exact element.
On Safari ShadowRoot.getSelection
is not supported and apparently document.getSelection
does not pierce the Shadow DOM, meaning you are just out of luck.
There is a standards proposal to fix everything with Selection.getComposedRange
, but it is not implemented anywhere yet. According to the discussion, they will work on a spec PR early to mid 2022.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With