automatorselectedtextjavascript-automation

Get the string from selected text/ highlighted text using JXA


I'm supper new here, either Javascript and JXA, so pardon me if I make some stupid questions. But I'm trying to figure out a way to get the string from the highlighted text using JXA - JavaScript for Automation, for Javascript can be recognized in Automator since Yosemite, I thought I can make something work with these: window.getSelection in:

function getSelectedText() {
  if (window.getSelection) {
      txt = window.getSelection();
  } else if (window.document.getSelection) {
      txt =window.document.getSelection();
  } else if (window.document.selection) {
      txt = window.document.selection.createRange().text;
  }
  return txt;  
}

This code is not mine, somebody posted this. But I've found out that I can't use window or document here in Automator to make change to Mac OS, so can someone show me how to convert this Javascript code into JXA which Automator can understand?

Thanks a lot!


Solution

  • In general, you can use the System Events app to copy and paste with any app.

    'use strict';
    
    //--- GET A REF TO CURRENT APP WITH STD ADDITONS ---
    var app = Application.currentApplication()
    app.includeStandardAdditions = true
    
    var seApp = Application('System Events')
    
    //--- Set the Clipboard so we can test for no selection ---
    app.setTheClipboardTo("[NONE]")
    
    //--- Activate the App to COPY the Selection ---
    var safariApp = Application("Safari")
    safariApp.activate()
    delay(0.2)	// adjust the delay as needed
    
    //--- Issue the COPY Command ---
    seApp.keystroke('c', { using: 'command down' }) // Press ⌘C 
    delay(0.2)	// adjust the delay as needed
    
    //--- Get the Text on the Clipboard ---
    var clipStr = app.theClipboard()
    console.log(clipStr)
    
    //--- Display Alert if NO Selection was Made ---
    if (clipStr === "[NONE]") {
    	var msgStr = "NO Selection was made"
    	console.log(msgStr)
    	app.activate()
    	app.displayAlert(msgStr)
    }

    For more info see: