0

I want to capture selected text from Etherpad. There is API methods available /getText that will return the entire text. My requirement is to get only selected text.

Thanks in advance!

Yogesh
  • 363
  • 3
  • 9
  • 22

1 Answers1

1

If you want to use the selected text in an outer frame, you could use a postMessage System.

exports.postAceInit = (hookName, context) => {
  window.addEventListener('message', function receiver(e) {
    // Data of Request
    let data = e.data;
    // Origin URL of Request
    let origin = e.origin;

    if(data == 'GET_SELECTION'){
      context.ace.callWithAce((ace) => {
        // Read current selection
        let rep = ace.ace_getRep();
        
        // Start of the Selection [x,y]
        let selStart = rep.selStart;
        // End of the Selection [x,y]
        let selEnd = rep.selEnd;

        // Read Lines of Pad
        let lines = rep.lines;

        let retVal = '';

        // Run through Selection
        for(let idx = selStart[0]; idx < selEnd[0]+1; idx++){
           retVal = retVal + lines.atIndex(idx).text;
        }
 
        // Send text to Receiver
        e.source.postMessage(retVal, origin);
      }, 'GET_SELECTION', true);
    }
  , false);
}

Receiver and Sender Site:

<script type="text/javascript">
    function sendMessage(message) {
        document.getElementById('etherpad').contentWindow.postMessage(message, '_URL OF YOUR ETHERPAD INSTANCE_');
    }
    function receiver(e) {
        // Read Data of Request
        let data = e.data;
        // Origin URL of Request
        let origin = e.origin;

        alert("GOT: " + data + "\nFROM: " + origin);

        e.source.postMessage('Thanks', origin);
    }

    // Listener gets Requests
    window.addEventListener('message', receiver, false);
</script>

<button type="button" onclick="sendMessage('GET_SELECTION')">GET SELECTION</button>

This code will get you the whole lines of text from the selection. If you want to get the exacts characters, you would need a second loop within the idx for-loop

Zumpfiii
  • 56
  • 1
  • 5
  • Hi @Zumpfiii, Is there any way to replace/modify the selected text with some other text and make that link as well? – Yogesh Nov 09 '21 at 06:37
  • 1
    Yeah you just have to use the ```editorInfo.ace_replaceRange(start, end, text)``` Function. But be careful, start and end are always arrays [x,y] like the rep.selStart Link to Documentation: https://etherpad.org/doc/v1.8.14/#:~:text=pad%27%20%2B%20message.padId)%3B%0A%7D%3B-,editorInfo,-editorInfo.ace_replaceRange(start – Zumpfiii Nov 09 '21 at 08:33
  • hey, have you integrated etherpad with react? – Geetanjali Katare Feb 24 '22 at 12:50