How to get the selected text or the inner html in Dart

1.4k views Asked by At

How to get the text or the inner html of the current selection by using dart:html? I use on-mouseup event of the div as the start point to do it:

<div on-mouseup="{{on_mouseup}}">
void on_mouseup(MouseEvent e, var detail, DivElement src) {
  final selection = window.getSelection();
  // do somthing 
  // ..
  // final selectedText = ..;

  window.alert("Selected text is $selectedText!");
}

Example:

enter image description here

The value of the variable selectedText should be 'window.getSel'

1

There are 1 answers

9
Günter Zöchbauer On BEST ANSWER
src.innerHtml` or `src.text
print(window.getSelection().getRangeAt(0).cloneContents().innerHtml);
print(window.getSelection().getRangeAt(0).cloneContents().text);

There is also a shadowRoot.getSelection() in PolymerElement.

print(shadowRoot.getSelection().getRangeAt(0).cloneContents().innerHtml);
print(shadowRoot.getSelection().getRangeAt(0).cloneContents().text);

I tried it with content outside the custom element, in the shadow DOM of the element and as child of the custom Element.

There are some issues what can be selected when the selection crosses the shadow boundary (immediately selects the entire content of the shadow DOM. Beside from that document.getSelection() and shadowRoot.getSelection() always return the same result.

It seems getSelection doesn't work when the end (mouse-up) is within the shadow DOM. When the selection starts in the shadow DOM and ends in the (child) content it works but not the other way around.

I think this is a bug.