ContentEditable in Shadow DOM?

2019-03-31 04:12发布

问题:

I'm trying to create a Polymer element for contenteditable.

I create a contenteditable div, place this.innerHTML there, and it becomes editable. All good with polyfills, e.g. in Firefox. But it doesn't work in Chrome 35 with native Shadow DOM.

Well, it is still editable, but neither document.execCommand nor window.getSelection is working.

  • document.execCommand does nothing.
  • window.getSelection().getRangeAt(0).toString() is defined but empty.
  • No error is shown.

So I cannot style the selection.

Does anybody know whether it's possible to make a custom editable element or not? What am I doing wrong? Maybe there's another way to work with contenteditable in modern/future web?

回答1:

According to the spec 1 selection is somewhat open ended for implementors. It does mention:

Accordingly, selections may only exist within one node tree, because they are defined by a single range. The selection, returned by the window.getSelection() method never returns a selection within a shadow tree.

The getSelection() method of the shadow root object returns the current selection in this shadow tree.

Have you tried the shadow root's getSelection()?