Copy with Selection Test [JXA]

Continuing the discussion from Copy with Selection Test [Sub-Macro]:

I was working on another project and needed this function entirely in my JXA script, so I wrote it and have published it in my GitHub Gist:

Copy & Get Selection to Clipboard JXA.js

~~~ VER: 1.1.1 Updated: 2016-06-18 ~~~

This JXA function provides the same result as the KM Sub-Macro shown above, except that it returns an empty string if there was no selection.

It can be easily used with a KM Macro, or wholly within another script.

####This function addresses two common issues:

  1. How to determine whether or not the user as made a selection
  2. Waiting for the App to complete the copy, but continue ASAP

If you have any questions, comments, bugs, or suggestions, please report them here. The Gist does not provide any email notification of comments.

Example Usage

'use strict';

var app = Application.currentApplication()
app.includeStandardAdditions = true

var mySelection = copySelection("Safari", 1)

function copySelection(pAppName, pTimeLimitSec) {
/*  VER: 1.1.1     DATE: 2016-06-18

PURPOSE:    Copy Selection to Clipboard, & Return Value

  •  pAppName        : Name of App in which to copy selection
                        • IF pAppName is invalid, script will stop with error msg
  • pTimeLimitSec    : Max number of seconds to wait for App Copy to complete
                        • usually 2-3 sec is adequate
                        • If you are expecting a short text selection and
                          possibly no selection, then 1 sec should work
  •  Items that were selected in the App (text, rich text, images, etc)
  • IF no selection was made, an empty string is returned
AUTHOR:  JMichaelTX (in most forums)
           Find any bugs/issues or have suggestions for improvement?
           Contact me via PM or at

  1.1.1  2016-06-18    ADD Parameter for pTimeLimitSec
  1.1    2016-06-17    ADD timeout loop to wait for App to complete copy
  1.0    2016-06-17    First Release