未加星标

A Beginners Guide to JXA, JavaScript Application Scripting

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二05 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

If you have ever done any scripting on the Mac, then you most likely have seen AppleScript . AppleScript has been the de facto standard for meshing applications together and for user interface scripting.

Since OS X 10.10 Yosemite , there is a second scripting language for user interface scripting: javascript for Automation (JXA) .

In this tutorial, I'll help you to learn this alternative to AppleScript with some real world examples.

Running JXA

There are many ways to run a JXA script. The standard way to run JXA script is with the Script Editor that is a part of the operating system.


A Beginners Guide to JXA, JavaScript Application Scripting
Script Editor Set for JavaScript (JXA)

With the list box at the top left corner, under the stop button, set to JavaScript instead of AppleScript , you have a full JavaScript interpreter. To access the current application for scripting, add these lines:

//
// Get the current application and set it up
// for scripting.
//
var app = Application.currentApplication();
app.includeStandardAdditions = true;

The first line will get the JXA object for the application running the code. The second line allows you to add dialog boxes and other goodies to that application object.

Now add this to the script:

//
// Send a message to the user.
//
app.displayAlert("This is a message");
A Beginners Guide to JXA, JavaScript Application Scripting
Message Example

When you run this, it will display a message dialog with the text “This is a message”.

If you want to pick from a list of items, add the following:

//
// Let the user pick from a list.
//
var lang = app.chooseFromList(['JavaScript', 'AppleScript', 'JXA'], { withPrompt: 'What is your favorite language?' });
app.displayNotification(lang, { withTitle: 'Language Chooser', subtitle: 'Your Choice is...' });

The chooseFromList() function takes an array of strings and an optional object with configuration options. The withPrompt configuration option allows you to set the text displayed above the list of strings. The string selected will be return.

The displayNotification() function is then used to display a notification with the information supplied to the user. You can set the title and subtitle of the notification with the configuration object.


A Beginners Guide to JXA, JavaScript Application Scripting
List Picker Example

When you press the run button (the right pointed triangle in the toolbar), you pick your favorite programming language in the dialog.


A Beginners Guide to JXA, JavaScript Application Scripting
Notification Displayed

When you select one, like JXA, your selection is then shown in a notification popup. If the user selects cancel in the dialog, the returned result will be the Boolean False.

If you need to get information from the user, use the displayDialog() function. With this function, you need to call it within a try...catch structure because if the user presses the cancel button, it will throw an error. Type in the following code:

//
// Get user typed information.
//
try {
var age = app.displayDialog('How old are you?', { defaultAnswer: "" });
app.displayNotification(age.textReturned + ' years old!', { withTitle: 'You are How old?' });
} catch(e) {
app.displayNotification('User Canceled', { withTitle: 'Error' });
}
A Beginners Guide to JXA, JavaScript Application Scripting
Getting Input from the User

By running that code, you will be requested your age in a prompt. When you type an age and click OK, it will show a notification asking your name. If you press Cancel, a notification with the text Error User Canceled shown.

A Classic Example

The classic example of program automation is to open iTunes , and play a song. In a new file called iTunesScript.scpt , add the following code:

//
// Get a application object for iTunes.
//
var itune = Application('iTunes');
itune.activate();
//
// Play a song.
//
itune.play();
//
// To pause:
// itune.pause()
//
// To stop:
// itune.stop()
//
//
// Get the current track information.
//
var track = itune.currentTrack()
var info = track.name() + " - " + track.artist() + " - " + track.album() + " - " + track.duration();
//
// Display the information to the user.
//
var app = Application.currentApplication();
app.includeStandardAdditions = true;
app.displayNotification(info, { withTitle: 'iTunes Song' });

This script will play the current song in iTunes and display the songs’ name, artist, album, and duration in a notification.


A Beginners Guide to JXA, JavaScript Application Scripting
iTunes Script

The basics for controlling an application is to get an application object, execute methods of the object to get the needed information or the desired effect. You can get information about each application objects valid methods from the File > Open Dictionary menu in the Script Editor .

If you want to run the script on a command line, you would type this command in a terminal window:

osascript -l JavaScript iTuneScript.scpt

The -l JavaScript tells osascript that the script is using JXA .

JXA in Alfred

In the download zip file, you'll find the QuickEditJXA.alfredworkflow Alfred 3 workflow.

This workflow allows you to copy a selection in one program, paste in to another program you setup before hand, and then copy the edits back to the original program.

This is very handy workflow that saves a lot of time. My preferred editor for making these quick changes is TextWell .


A Beginners Guide to JXA, JavaScript Application Scripting
Alfred Workflow: Quick Edit in JXA

The green set of blocks copies the already selected text and places it in the editor. In Alfred , one action can split into any number of other action chains. In this one, it splits two ways.

The topmost line of action is performed first, and then it backs up to the second line of action. The top line’s first action is a JXA script:

function run(argv) {
var query = argv[0];
//
// Get the name of the current application.
//
var system = Application("System Events");
var proc = system.processes.whose({ frontmost: {'=': true } }).name();
return proc;
} This JXA script will get the topmost application name from System Events sub-process. Line 7 gets an application object on System Events. Line 9 searches the array of active processes with

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: JavaScriptJavaApple
分页:12
转载请注明
本文标题:A Beginners Guide to JXA, JavaScript Application Scripting
本站链接:http://www.codesec.net/view/480697.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(31)