Reputation: 981
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!
Upvotes: 13
Views: 3827
Reputation: 15413
The state of affairs as of Dec 2023:
ShadowRoot.getSelection
is a non-standard API.
Selection.getComposedRanges
is a standards proposal to support selection with Shadow DOM.
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, Selection.getComposedRanges
is supported as of v17. On versions before that, ShadowRoot.getSelection
is not supported and apparently document.getSelection
does not pierce the Shadow DOM, meaning you are just out of luck.
Upvotes: 14
Reputation: 1273
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
Upvotes: 2
Reputation: 31
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.
Upvotes: 3