JXA - JavaScript for Automation - From the Start

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?

It defines which syntax to use when presenting the dictionary entries. Change the values and see what happens.

I’m not going to way in much on this topic, for one thing I don’t know much JXA. But here are some quick thoughts:

It is easier for people to ignore a single long topic. If this topic is designed to solicit answers to the question of how to document JXA appropriately, then a single topic makes sense, and one topic for each possible thing to document would be much more noisy.

As @ComplexPoint says, JXA is the same language as JavaScript in the browser or JavaScript in a Custom HTML Prompt. This is true in the same way you can program a Mac or Windows or Linux machine in C++ - it is the same language, but the enclosing environment (platform, libraries, capabilities, etc) is very different.

The results of this topic would presumably best be a wiki page. There is already a wiki page: https://wiki.keyboardmaestro.com/JavaScript_for_Automation and it would be a good host for whatever information, or if necessary the information could be broken into multiple pages. Possibly there should be a https://wiki.keyboardmaestro.com/JavaScript page (not currently) that described information about the language and the various different environments it appears in.

1 Like

2 posts were split to a new topic: Making Changes to Your Topic

I moved the above two posts to the “meta” category (which is the Category dealing with this forum), since they are about forum issues, and have nothing to do with this topic, JXA.

(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).

A footnote from experimenting with Sierra:

It is indeed using Safari 10, so in JavaScript for Automation, we can now (given MacOS Sierra) write things like:

1 Like

Awesome!

Is this going to require Sierra, or will an update be made available to El Cap and Yosemite? I don’t know how Apple handles these things.

Good question … not sure …

###To all concerned:

We've had a bit of discussion about the best way to provide JavaScript for Automation (JXA) support, both for ourselves and those new to JXA.

I sense a consensus that having one long topic is probably not the best approach. If anyone disagrees that this is the concensus, please feel free to object and state your opinion.

Having thought about it for a while, IMO we should avoid reinventing the wheel, and try to make use of the existing JXA wiki:

###JavaScript for Automation Cookbook
From its Foreword · dtinth/JXA-Cookbook Wiki

####Contributions Welcome
But still, I don't have everything figured out. I am learning, like you. There is a lot to be discovered in this new JavaScript environment. So, to make it easy to edit and collaborate, I've put the contents on GitHub wiki, which anyone can contribute.

So, if you have anything to add to this cookbook, just hit that edit button. If you found any typo, also hit that edit button. And if you have trouble understanding some part of the cookbook, you can open a GitHub issue on this repository.

So, please enjoy automating your Mac with JavaScript, and hope you have fun! :smiley:

            —Thai Pangsakulyanont
                2014-11-01

Here are the advantages I see:

  • It already has a solid base of JXA information
  • The owner, Thai, seems very open to contributions by others
  • It is already fairly well known to the JXA community
  • It is more likely to attract JXA users from everywhere, not just those who use KM
  • It is part of a GitHub reprosiitory, which has a decent facility for Q&A:
    • Issues · dtinth/JXA-Cookbook
    • Includes option to subscribe to new questions/posts
    • Has a good editor for posts, based on markdown
    • Issues can be marked "closed" when resolved/answered.
  • It is easy to provide links to anything, like the KM forum, wiki articles, etc
  • If we think it would help, we could even propose add a section on KM to the JXA wiki

The only downsides I see are:

  1. Not as much control as we would have here
  2. Creates another web site we would need to watch/subscribe to.

Your thoughts?

Apart from the shift to Safari 10’s ES6 JavaScript interpreter, the only other change to JXA that I immediately notice is a couple of new methods in the ObjC component of the Automation object - some help for dealing with ObjC functions which include reference types in their arguments.

If you run the code in the previous post (to inspect the broad contours of the automation object), you now see , in addition to the earlier listing:

ObjC.castObjectToRef 
ObjC.castRefToObject 

Perhaps useful, for example, with ObjC error reference handling.

1 Like

@DanThomas and all:

I just added a new forum tag "learning" that I think will really work well for your objective.
If we start a new topic for each JXA question/issue/learning example, and tag it with "jxa" and "learning", then anyone can quick bring up all JXA learning topics with this search:
tags:jxa tags:learning

Your thoughts?

Probably a good idea, although I never think to use tags. But others will probably appreciate it.

It's just a matter of habit.
Of course, I was already a big tag user from my Evernote usage.
I find them very helpful. Try the search now to see the benefit:
tags:jxa tags:learning