shadowRoot.getSelection()?
Asked Answered
T

3

12

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!

Trigeminal answered 28/5, 2020 at 0:3 Comment(4)
Answering my own question: it looks like for working inside the shadowRoot, one should use shadowRoot.getSelection() on Chrome, and document.getSelection() on other browsers.Trigeminal
did document.getSelection() return nodes inside the shadow root on Safari & FF?Neurophysiology
Justin, "document.getSelection()" works on FF; I haven't tried it on Safari, but I think I was told it did.Trigeminal
@JustinFagnani it does work in FF but it shows only container of shadow dom in Safari.Perfidious
L
12

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.

Logistics answered 29/12, 2021 at 18:5 Comment(0)
W
3

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.

Whiteheaded answered 13/6, 2020 at 12:53 Comment(1)
When I tested in Firefox, this.shadowRoot.getSelection was undefined. The docs page has it listed as "non-standard": developer.mozilla.org/en-US/docs/Web/API/ShadowRootLogistics
B
2

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

Bearwood answered 12/11, 2021 at 13:22 Comment(1)
there is no thread there: pasteboard.co/SuKLFLVF3h5D.pngSwipe

© 2022 - 2024 — McMap. All rights reserved.