JXA - JavaScript for Automation - From the Start

Continuing the discussion from MACRO: Make Macro Alias:

I thought we should start a new topic on this, although there are multiple topics on this already, I think it would be nice if someone who is just starting out could document their experiences, and perhaps help others learn. What do you think? You game?

JXA (JavaScript for Automation) is the JavaScript version of what AppleScript can do. There’s no real difference between JXA and standard JavaScript, except for the special libraries that are available, and the environment under which it is run.

I’ll tell you right up front - getting up to speed is a daunting task, because the documentation, when there actually is some, is extremely sparse. That’s why I’m hoping you’re willing to document your experience, here in this topic.

I will answer as many of your questions as I can, as will others on this forum. I’m committed to getting this documented, if you are. So that means, please bug me with every question you can think of, when you run into walls.

Anyway, here’s the awesome (sarcasm) documentation Apple has:

OS X 10.10 Release Notes
OS X 10.11 Release Notes
Mac Automation Scripting Guide

And here’s some good resources:

JavaScript for Automation Cookbook
JXA Resources
Some of My Stuff

Lastly, I use Atom as my preferred editor. I truly wish I had documented what it took to get it set up for JXA, but unfortunately I didn’t. So if you wanted to tackle this also, it’s another thing we could document from scratch.

Dan

2 Likes

Well, IMO as supported by Apple documents, there is a huge difference:

JXA fully supports Mac automation of applications and the macOS, and can run standalone, even be used to created an app itself.

  • It does NOT require a browser.
  • It does NOT have direct access to the web page DOM, without using a browser app like Safari or Chrome.
    • JXA, just like AppleScript, has full access to everything on the Mac that the user does.

Standard JavaScript can run only in a browser, and has NO access to other Mac apps and very, very limited access to the files on your Mac.

However, JXA and standard, browser-based, JavaScript both share the same core JavaScript language.

Perhaps you meant “the environment under which it is run.” to cover this, but I don’t think that is obvious, and could be misleading to new users of JXA.

I’m pretty sure you will agree with the above. I just wanted to be clear.

Dan, I have mixed feelings about this.

One one hand, it is good to have a topic dedicated to learning JXA.

OTOH, there are already several topics for this, and a forum topic is a poor tool to establish a good reference for any subject, including JXA. A wiki would be a much better tool.

There is already one good JXA wiki, but it is not well suited for Q&A (although that is supported:

###JavaScript for Automation Cookbook by dtinth (GitHub wiki)
.

Here is my reference list, getting starting list:
###JXA Resources by JMichaelTX

If you (and others) are serious about creating a good JXA knowledge base, then we may want to consider creating a wiki eBook:

https://en.wikibooks.org/wiki/Main_Page

I’m open to discussion on this topic.

Oh yeah, I remember this discussion from before.

Semantics. The point is, if you know JavaScript, you don’t have to learn another language. Syntax is the same. The differences are what libraries are available, and under what environment it is run.

If you disagree, fine. I’m not continuing this discussion, because I saw how it degraded last time. But I’m right. gd&r.

A Wiki would be a good place to gather all the information, once we’ve captured it. But for the Q&A it would take to get started, I think a forum is a better place. It’s just one topic, after all.

But the point will be moot if he doesn’t want to do it, and I have a feeling that will be his response, judging by some of his other comments about how busy he is.

It is more than semantics. It is about being clear about the differences.
Allowing someone to think JavaScript and JXA are mostly the same will lead to confusion.

The point about the language is somewhat true, but ONLY for the core JavaScript. The biggest challenge is learning the application commands (app dictionary) to use in JXA.

The point I would make about language is this:

  • If you don’t know AppleScript, and you want to automate your Mac with scripting, then JXA (JavaScript) is a better choice, particularly if you already know browser-based, core, JavaScript.
    .
  • You can do everything in JXA that you can in AppleScript.

We’ve actually already been down that road with:

The issue with having one topic for such a broad subject, with lots of different questions, is that it quickly becomes hard to find a particular question/issue, and questions are often repeated because many people won’t take the time tor read a long topic.

I agree a forum is better for Q&A, but we really need for each specific question/issue to be a different topic.

So I see at least two alternatives to one long topic:

  1. Make each specific JXA question/issue a different topic, and tag all with the existing tag “jxa”
  • Maybe have one primary topic, open only to selected users, to provide an overview and instructions.
    .
  1. Create a new forum category for JXA
  • Of course, @peternlewis would have to approve this, and in general he has resisted adding new forum categories

I have no idea what you are talking about here. Perhaps best to PM me.

OK, I don’t really care either way. Whatever you want is fine with me.

Yes, avoiding confusion is good. Allowing someone to think using JavaScript in a browser is the same as using it to automate applications would be confusing (and wrong). So I agree that the clarification should be made.

However, you’re wrong about one thing. They are the same language. Any argument you make otherwise is just wrong.

Example: Microsoft is making C# available on OS/X. It is most definitely the C# language. However they’re not porting most of the C# libraries that make using C# worthwhile. So I would be wrong in saying that using C# on OS/X is the same as using it onWindows. But I would be correct in saying that it’s the same language.

In fact, I would expect to need to learn new core functionality when using C# on OS/X. It’s a different environment. The same is true for JavaScript vs. JXA.

Same language. Different context.

OK. I disagree, but won’t debate that with you here, as long as we have made it clear what the differences are, and it sounds like we have agreement about that.

The main question at this point is how do we setup a system for supporting JXA questions/issues. I suppose one could ask, should we do it here, since this is moving in a major way from the core Keyboard Maestro support.

The same question could be asked about supporting AppleScript. But so far Peter (and Chris) have not setup anything specific for that.

Let me throw this out for discussion:

  • Why do we need, or, what are the advantages of, have one long topic on JXA, vs having a separate topic on each specific issue/question (like is done now for AppleScript), and just tag each topic with “jxa” ?

Based on these questions, and existing topics, we could, if desired, then create one or more articles in the KM Wiki, or start a separate wiki.

We do indeed.

As I said previously, (or I was trying to say previously), I don’t have a good answer. So I’ll go with whatever you, Peter, and whoever has an opinion, decides.

@peternlewis & @ccstone: What are your thoughts on this?

I’d also love to hear from anyone who has done this sort of thing before. If you have, please share your experience/suggestions.

Hey Guys,

Well…

I think one long topic has proved itself to be less than clear and concise – and probably very intimidating for beginning users.

I think the learning topics should basically link to other stuff in a clear fashion that generally builds from basic to complex.

I think we might as well just tag things AppleScript and JXA.

We can always move topics when warranted.

-Chris

Dan Thomas puts it very well and carefully - but perhaps what people mean by ‘language’ depends on their background:

  • In technical terms, language will mean a syntax and an interpreter or compiler
  • From a consumer perspective, it may mean something like a product.

Both usages are understandable, and perhaps we can skip jostling over them by avoiding the word ‘language’ and simply looking at:

  1. Syntax and interpreter
  2. Embedding
  3. Libraries

Syntax and interpreter

The syntax and interpreter used (at the moment) by JXA is the Safari 9 ES 5 JavaScript interpreter

http://kangax.github.io/compat-table/es6/#safari9

(one would hope that MacOS Sierra will be adopting the ES 6 Safari 10 JavaScript interpreter, which brings tail recursion optimisation, simpler lambdas, etc etc).

http://kangax.github.io/compat-table/es6/#safari10

Embedding

JavaScript is an embedded scripting language, and Apple’s interfaces include the JSContext interface for embedding a Safari JavaScript execution environment into various applications. Safari and JXA embed the same build of the same JavaScript interpreter in different contexts - one in a browser, one in a JSContext accessible to Script Editor, osascript etc.

Libraries

JXA’s JSContext doesn’t include the web object libraries in Safari’s JSContext, but it has one library object of its own: the Automation library object.

The contents of this are:

Automation
    Application
        currentApplication
    Library
    ObjC
        $
        Ref
            equals
        bindFunction
        block
        deepUnwrap
        dict
        import
        interactWithUser
        registerSubclass
        super
        unwrap
        wrap
    ObjectSpecifier
    Path
    Progress
    delay
    getDisplayString
    initializeGlobalObject
    log

(You can generate this listing yourself by running the following code in Script Editor, which will place it in the OS X clipboard.)

var strClip = (function () {
    'use strict';


    var lstSeen = ['Automation'];

    function keyTree(o, strIndent) {
        var indent = strIndent || '',

            ks = Object.getOwnPropertyNames(o)
            .filter(function (k) {
                return (['name', 'prototype', '__private__']
                    .indexOf(k) === -1 &&
                    lstSeen.indexOf(k) === -1) ? (
                    lstSeen.push(k),
                    true
                ) : false;
            })
            .sort();

        return ks.length ? (
            ks.map(function (k) {
                return indent + k + '\n' + keyTree(o[k], indent +
                    '    ');
            })
            .join('')
        ) : '';
    }


    return 'Automation\n' + keyTree(Automation, '    ');

})();

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

sa.setTheClipboardTo(strClip);

strClip
3 Likes

Very cool, very well stated, and welcome back. :slight_smile:

2 Likes

I tried it in Script Editor and got the desired result. I am curious though. I have Script Editor version Version 2.8.1 (183.1) is that the latest version for El Capitan 10.11.6?

The reason I ask: The other day I was trying some JavaScript examples in Script Editor and I noted there was a pop up menu at the top I never noticed before. So I am wondering where that could have gone? The pop up menu was in the menu bar of the editor and listed Apple Script, Java Script, and I believe it was ObjC. It looked like a new editor.

Are you talking about this?

Not sure when they added it (I suspect Yosemite), but it is in the current version, which is what you have.

Nope Dan. It was a white menu agains the toolbar. It looked different and had ObjC in the menu too and no “Apple Debugger”. Looked like a completely new tool.

Perhaps Script Editor's dictionary browser ?

(File > Open Dictionary, and then choose a target application)

That’s it. Why is that in the dictionary?