etherpad

Etherpad: How to capture selected text from etherpad


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!


Solution

  • 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