Learning & Using AppleScript & JavaScript for Automation (JXA)

In my use case I’m building a HTML file that needs to survive exit of the script for display purposes. So that’s why I need the auto-clear.

One solution to this is simply to have your script clear the file at the start. So yes, you’ll leave the file hanging around, but only one of them.

1 Like

This is what I usually do.

If I need to use reuse a temporary file in a workflow and don't want it rewritten by any old script I'll give it a unique name.

set curlDumpFile to (path to temporary items from user domain as text) & "curlDump.txt"
set tempFile to (path to temporary items from user domain as text) & "temp.txt"

The temp.txt file is used by any script when I don't care about the contents after the script is finished. Writing to it destroys any previous content — unless I deliberately append to the file.

Something like curlDump.txt I might want to be able to examine and do something with in-between the the times I write to it.

-Chris

Hey Chris, thanks again for a cool handler.

The handler works OK, but if you need to call it from inside a tell block, I found you need to use the "my" command, or AS throws an error.

The "my" command always works, so that's probably the best practice to use.

my setKMVar({varName:"Test1", varValue:"I am NOT nuts!"})

Hey JM,

I wouldn't call it a "best practice".

In a handler-call within a tell-block this would generally be:

my <hander-call>

or

<hander-call> of me

but

Tell me to …

or

Tell me
…
end tell

also work — and might be more clear in some cases.

I generally prefer the latter version, because I find it more readable.

These methods are only necessary to break you out of a tell-block or another handler and address the top-level of the script where the handlers are defined.

When you're already at the top-level of the script there's no need to reference it.

It is very easy to forget to add the routing "of me" or "my" to handler-calls when they're needed, and then of course you get an error.

------------------------------------------------------------
# Works fine at top-level of script.
y("Sometimes you feel like a nut!")

tell application "TextEdit"
  # TextEdit knows nothing of command y(b).
  # The handler-call y(…) must be told where to look for itself.  (Top-level of script.)
  # The avialable forms of re-scoping the call:
  
  tell me
    set theString to y("Sometimes you feel like a nut!")
  end tell
  
  tell me to set theString to y("Sometimes you feel like a nut!")
  
  set theString to my y("Sometimes you feel like a nut!")
  
  set theString to y("Sometimes you feel like a nut!") of me
  
end tell

------------------------------------------------------------
--» HANDLERS (can have dependencies on other handlers)
------------------------------------------------------------
on x(a)
  set upperCasedString to do shell script "echo " & (quoted form of a) & " | tr '[:lower:]', '[:upper:]'"
  return upperCasedString
end x
------------------------------------------------------------
on y(b)
  return x(b)
end y
------------------------------------------------------------

-Chris

Since using " my handlerFunction" always works, it seems to me that if one gets into the habit of always using "my", and therefore never fails, then it would be a "best practice".

I'd rather not have to remember when it is necessary and when it is not.

To each his own. :smile:

Rob,

Thanks again for your JXA examples.

I think I'm missing something basic, because when I try to run any of the kmVar scripts, I immediately get a runaway script -- spinning beachball, and have to force quit.

Also, I don't understand the purpose of enclosing all of the scripts in a function run( ).

Can you please point me in the right direction? :smile:
Thanks.

The kmVar scripts ?

Is it JXA you have in mind, or browser JavaScript ?

(Probably best to post an example action/macro)

More broadly, the first script to run when exploring any Javascript context - JXA or browser, is:

this

For JXA, for example, just create a Script Editor script consisting of that single key word and run it to see the result.

What you will see is that a JavaScript environment, name space, or context (call it what you will):

  1. Exposes rather a lot of global names
  2. Allows you complete freedom to pollute/confuse the global name space with any variables of your own, or be confused if you trip over an unexpected global variable name clash.

This is why it’s generally good practice to wrap your work in a containing function, localising your own variable declarations. JXA offers the standard osascript run() function (on run in AS), but a more general wrapping pattern, which will work in browser JavaScript or JXA is an immediate execution of an “anonymous” (ie unnamed) function.

(function () {
    var ...

    return ...
})();

Where the final pair of (potentially empty) parentheses immediately call the function that has just been defined.

(If you don’t do this, you may be inadvertently polluting the global name space with persistent name bindings, which may cause unexpected or unintended effects downstream)

Rob, thanks for the additional insight.
I have not seen the important point about always using a function clearly made anywhere else. I guess that is one, of many, area(s) that is much different from AppleScript.

As indicated in the link to your post in my quote, what I was talking about is is running exactly your code, in the above "[slightly expanded example][1]" post, in the Apple Script Editor.

When I just paste in your code, compile and run I get the spinning beachball, and have to force quit the Script Editor.
After some experimentation last night, I found I had to add these lines of code at the top, above your function run():

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

Then the script ran fine. :smile:

I noticed that you sometimes put current app statement inside of the function like this:

function run() {

  var a = Application.currentApplication(),
    sa = (a.includeStandardAdditions = true, a);

Several questions to help clear the fog in my head:
Running JXA in the Script Editor:

  1. Do you ever put any statements outside of the function run(), or is your code always inclosed within it?

  2. Is the function run() always executed without calling it?

  3. What is the advantage of creating/using the sa variable?
    (I'm sure there is one or you wouldn't have done it)

Thanks. I really appreciate your help and time.
Sorry for all the newbie questions, but now that I have upgraded to Yosemite I am trying to move from AppleScript to JXA as soon as I can.

Oh, that reminds me. Do you know of any books on JXA specifically?
We've discussed books on JS before, and there are a number of those available.
But in my search last night I could not find any dedicated to JXA.

TIA.
[1]: http://

  1. You could certainly use the pattern of treating the run() handler as a kind of main() function, with other functions declared outside (subject to the earlier caveats about keeping JavaScript’s global namespace simple).

  2. I think osascript does tend to treat unwrapped code as implicitly contained by a run handler. One reason, perhaps, for preferring the anonymous function call, though the stakes are certainly not high on short and simple scripts

  3. The sa variable just expresses a personal preference for functional rather than imperative patterns, and for avoiding the mutation of variables after the name declaration stage. The sa name helps to remind me that I am looking at an instance of Application in which .includeStandardAdditions has been set to true. Not a necessity – just one of several possible approaches to composing code and using names.

Thanks, Rob.

So is there ever a need, a use case, to put code outside of the run() handler?

Not really, unless to simplify readability.

For these kinds of fundamentals (scope, namespace management, closures etc) I think the Crockford is good.

PS, I think it’s probably particularly helpful to get a sense of closures (nested functions) in JavaScript.

Essentially, name-bindings move inwards but not outwards. Nested functions have full access to all the names of variables in the functions which enclose them, but not vice versa.

To put it another way, parents are transparent to their children, but children are opaque to their parents (pretty much as in human societies, perhaps :- )

This can be very useful.

1 Like

Some JavaScript related education discussed in Date Calculations:

2 Likes

Rob, just rediscovered your JXA code for getting paths, in the various forms.
This is very helpful. :+1:

Thanks.

Are we expecting any update to KM which will speed up the processing of AppleScripts on KM Engine?

Hard to imagine how that could be done ...

Depending on what you are doing, Javascript can be faster for some purposes.

1 Like

I don't know about any changes to Keyboard Maestro, but, the following could speed up your scripts:

  1. Save the script text in the Action to a compiled file (.scpt), and change the KM Action to use that file.
  2. Execute the script file using the Apple Scripts menu, or FastScripts.
  3. Rewrite the script to avoid known bottlenecks like the Finder.
  4. Make use of ASObjC.
  5. Use professional script libraries (like those from @ShaneStanley) and/or Scripting Additions (like Satimage.osax).
  6. Finally, review and optimize the design of your script.
1 Like

Basically, no. @JMichaelTX gives a lot of good advice on possible ways to improve the performance, but no changes to Keyboard Maestro are likely to help you.

You need to figure out what is causing the performance issue, there are a bunch of plausible places to look:

  • Keyboard Maestro has some overhead. Run a trivial script and you can see the base overhead.
  • Compiling the script can be expensive - Keyboard Maestro will compile your script from text each time it is run unless you select a compiled script file.
  • AppleScript is relatively slow
  • AppleEvent interprocess communication is relatively slow
  • The script itself could be using poor algorithms
  • You could buy a faster Mac, or one with more memory, or a faster HD, depending on what the bottlenecks are.

There are many ways you might improve the performance of a macro that is executing an AppleScript, but there are no plans to make Keyboard Maestro magically run an AppleScript faster.

What?!? An online study course for AS beginners? Where's the PayPal link?

Seriously, a wiki or perhaps a step further, a devoted space for us beginners (dedicated Outback Lounge space?) to gather and learn from each other along with the various AS bits scatter around this forum Collected and Organized would be useful and valuable.

This as in other places (here and outside this forum) is a mix of listening in on the hobnobbing among wizards from which some productive gleaning can come and some really well written 101 materials.

And yes I recognize this is a BIG ask as everyone has a life and this is forum is fundamentally based on acts of generosity of which fortunately there is very much.

I for one would paid a good fee or ongoing charge to participate. Money aside, someone would need to have a deep interest in or commitment to educating to take this on. Being very skilled in an art and communications that leading others to developing their skills are very different activities especially given how differently people develop.

1 Like