question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to get selected text

See original GitHub issue

How can I get the selected text in the editor? I checed the code, it call document.getSelection(), how can I get it manually.

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:1
  • Comments:6

github_iconTop GitHub Comments

1reaction
gevgasparyancommented, Jun 28, 2022

Hi Here is my workaround

import React, { useRef } from 'react';
import { StyleSheet, View } from 'react-native';
import { actions, RichEditor, RichToolbar } from 'react-native-pell-rich-editor';

const RichTextInput: React.FC = () => {
  const richText = useRef<RichEditor | null>(null);

  // Call this method to inject script and get selected text
  const onInjectJavascript = () => {
    const script = `(function() {
      var value = window.getSelection().toString() || '';
      window.ReactNativeWebView.postMessage(JSON.stringify({ data: {type: 'SELECTION_CHANGE', value } }));
      void(0);
    })();`;
    richText.current?.injectJavascript(script);
  };

  // Callback function to get selected text
  const handleOnMessage = (event: { type: string; id: string; data?: any }) => {
    if (event?.data?.type === 'SELECTION_CHANGE') {
      const selected = event?.data?.value;
      console.log('Selected text', selected);
    }
  };

  return (
    <>
      <View style={styles.toolbarContainer}>
        <RichToolbar
          style={styles.toolBar}
          unselectedButtonStyle={styles.toolbarIcon}
          selectedButtonStyle={styles.toolbarIcon}
          editor={richText}
          actions={[actions.setBold, actions.setItalic, actions.setUnderline, actions.insertLink]}
        />
      </View>
      <View style={styles.editorContainer}>
        <RichEditor
          placeholder={'Enter a message'}
          ref={richText}
          onMessage={handleOnMessage}
          androidHardwareAccelerationDisabled={true}
        />
      </View>
    </>
  );
};

const styles = StyleSheet.create({
});

export default RichTextInput;

injectJavascript method does not exist in node_modules/react-native-pell-rich-editor/src/RichEditor.js and you have to add in manually Add these lines in RichEditor.js

injectJavascript(script) {
    return this.webviewBridge.injectJavaScript(script);
}

To add injectJavascript automatically you can use postinstall script in package json

package.json

...
"postinstall": "./update_modules.sh"

Create update_modules.sh and add these lines

sed -i -e "s/render() {/injectJavascript(script) {\n\\t\\treturn this.webviewBridge.injectJavaScript(script);\n\\t}\n\n\\trender() {/g" node_modules/react-native-pell-rich-editor/src/RichEditor.js
 sed -i -e "s/preCode: (/injectJavascript: (script: string) => void;\n\n\\tpreCode: (/g" node_modules/react-native-pell-rich-editor/index.d.ts
1reaction
NicholasBoccuzzicommented, Apr 27, 2022

Having the ability to get both the selected text, surrounding html and character range would be very helpful.

For example: <p>NORMAL TEXT. <b>BOLD TEXT.</b></p>

If we select “BOLD TEXT” in the editor, it would be awesome to have a method that could return the selected text and even more helpful if there was a method that could return <b>BOLD TEXT.</b>.

React Native Quill editor has the ability to return the selection range. ItsonSelectionChange method will return data like this: {"oldRange": {"index": 19, "length": 6}, "range": {"index": 18, "length": 7}, "source": "user"}

Read more comments on GitHub >

github_iconTop Results From Across the Web

How do I get the text value of a selected option?
Select elements typically have two values that you want to access. First there's the value ... The second is the text value of...
Read more >
Get selected text from a drop-down list (select box) using jQuery
If you already have the dropdownlist available in a variable, this is what works for me: $("option:selected", myVar).text().
Read more >
How to get selected text from a drop-down list using jQuery?
How to get selected text from a drop-down list using jQuery? ; By using val() method : The val() method is an inbuilt...
Read more >
How to Retrieve the Text of the Selected option Element in a ...
In this article, we'll look at how to retrieve the text of the selected option element in a select element with JavaScript. Use...
Read more >
Window.getSelection() - Web APIs | MDN
The Window.getSelection() method returns a Selection object representing the range of text selected by the user or the current position of ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found