请选择 进入手机版 | 继续访问电脑版

技术控

    今日:235| 主题:53470
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] A Beginners Guide to JXA, JavaScript Application Scripting

[复制链接]
依旧爱你 发表于 2016-10-10 19:25:15
228 4

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
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

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:
  1. //
  2. // Get the current application and set it up
  3. // for scripting.
  4. //
  5. var app = Application.currentApplication();
  6. 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:
  1. //
  2. // Send a message to the user.
  3. //
  4. app.displayAlert("This is a message");
复制代码
   

A Beginners Guide to JXA, JavaScript Application Scripting

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:
  1. //
  2. // Let the user pick from a list.
  3. //
  4. var lang = app.chooseFromList(['JavaScript', 'AppleScript', 'JXA'], { withPrompt: 'What is your favorite language?' });
  5. 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

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

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:
  1. //
  2. // Get user typed information.
  3. //
  4. try {
  5.         var age = app.displayDialog('How old are you?', { defaultAnswer: "" });
  6.         app.displayNotification(age.textReturned + ' years old!', { withTitle: 'You are How old?' });
  7. } catch(e) {
  8.         app.displayNotification('User Canceled', { withTitle: 'Error' });
  9. }
复制代码
   

A Beginners Guide to JXA, JavaScript Application Scripting

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:
  1. //
  2. // Get a application object for iTunes.
  3. //
  4. var itune = Application('iTunes');
  5. itune.activate();

  6. //
  7. // Play a song.
  8. //
  9. itune.play();

  10. //
  11. // To pause:
  12. // itune.pause()
  13. //
  14. // To stop:
  15. // itune.stop()
  16. //

  17. //
  18. // Get the current track information.
  19. //
  20. var track = itune.currentTrack()

  21. var info = track.name() + " - " + track.artist() + " - " + track.album() + " - " + track.duration();

  22. //
  23. // Display the information to the user.
  24. //
  25. var app = Application.currentApplication();
  26. app.includeStandardAdditions = true;

  27. 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

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:
  1. 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

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:
  1. function run(argv) {
  2.         var query = argv[0];

  3.         //
  4.         // Get the name of the current application.
  5.         //
  6.         var system = Application("System Events");

  7.         var proc = system.processes.whose({ frontmost: {'=': true } }).name();

  8.         return proc;
  9. }
复制代码
  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 a .whose({ frontmost: {'=': true}}) command that finds the process with the frontmost property set to true. It then returns that process’ name.
   A JXA script in Alfred has to have the function run() that accepts an array of inputs. Whatever this function returns is then passed on to the next block in the workflow: a write to file command. This saves the current application’s name to the file for getting back to this application after editing.
   The second line of action calls the following JXA script:
  1. function run(argv) {
  2.         var editorName = argv[0];

  3.         var ed = Application(editorName);
  4.         ed.activate();
  5. }
复制代码
  The name of the editor gets passed to it from the previous Arg and Vars block. The editor application set by the user in the environment variables section of the Alfred workflow . Line 4 gets the application object for the editor and Line 5 activates the editor.
   On the paste action (the purple blocks), there is one JXA routine:
  1. ObjC.import('stdlib')

  2. function run(argv) {
  3.         var app = Application.currentApplication();
  4.         app.includeStandardAdditions = true;

  5.         var dataDir = $.getenv('alfred_workflow_data');

  6.         var handle = app.openForAccess(dataDir + "/process.txt");
  7.         var prog = app.read(handle);

  8.         var dest = Application(prog.trim());
  9.         dest.activate();

  10.         return ";
  11. }
复制代码
  Line 1 includes the stdlib which is the Objective C library for standard system access. JXA allows you to use any library that is on the system for use in your scripts. You can literally write a full application in just JXA !
   Lines 4–5 gets the current applications object and sets it up for scripting. Line 7 uses the stdlib to get the environment variable setup by Alfred : alfred_workflow_data . This environment variable gives the path to the data directory for the current workflow.  
   Line 9 opens the file process.txt in the workflow’s data directory and Line 10 reads it’s contents. Lines 12–13 brings the application to the front.
   Once the original application is at the front, a delay waits for the operating system to catch up, and then the workflow issues a cmd-v to paste it into the application.
   The original version of this workflow made use of PHP and Applescript . By using JXA , this version of the workflow runs much faster and more reliably. In like manner, you can use JXA in other programs as well. Keyboard Maestro , Hazel , and TextSoap , by use of an Automator script, just to name a few.
  Further Reading

   You can also find more information about JXA from these websites:
  
       
  • Apple Developer Notes on JavaScript for Automation   
  • JXA Cookbook   
  • Dan Thomas’ JXA Examples and Useful Routines   
  • Keyboard Maestro Wiki on JXA  
  Conclusion

   In this tutorial, I've shown you how to make use of JXA in the Script Editor , in the command line, and in an Alfred workflow  . Now that you know how to use JXA on your Mac, you can make some useful scripts for automating tasks.  
  Let me know,  in the comments below, what you create.



上一篇:Microservices in Flask
下一篇:Real-time applications using ASP.NET Core, SignalR & Angular
Music_life 发表于 2016-10-10 22:30:22
是爷们的娘们的都帮顶!大力支持
回复 支持 反对

使用道具 举报

月上舞袖 发表于 2016-11-7 13:39:38
来,来,干了这杯翔!
回复 支持 反对

使用道具 举报

爱看美女 发表于 2016-11-18 10:58:51
只想优雅转身,不料华丽撞墙。
回复 支持 反对

使用道具 举报

左眼角的淚痣 发表于 2016-11-18 22:50:52
众里寻他千百度,蓦然回首在这里!
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )

© 2001-2017 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表