big lep
big lep

Reputation: 887

Using OS X JavaScript for Automation (JXA) to listen to "open location" Apple Event

I am using OS X JavaScript for Automation (JXA), and I want to be able to capture the "open location" Apple Event.

Per http://www.macosxautomation.com/applescript/linktrigger/ , I have setup a customer URL handler. How do I do the equivalent of

on open location this_URL
  ...
end open location

with JXA? I tried all of the following, but could not get any of them to execute:

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

function run() {
   app.displayDialog(JSON.stringify(arguments));
}

function openLocation() {
   app.displayDialog(JSON.stringify(arguments));
}

function openDocuments() {
   app.displayDialog(JSON.stringify(arguments));
}

function onOpenLocation() {
   app.displayDialog(JSON.stringify(arguments));
}

Apple's JXA docs (https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/OSX10-10.html#//apple_ref/doc/uid/TP40014508-CH109-SW15 ) don't discuss how to handle the open location event. My script would get opened because I could get an alert to display if I added it outside the functions. I just couldn't get a function to execute and be passed in the URL.

I am working around this by having a AppleScript handler that that then invokes my JXA code, but this is certainly less than ideal.

I also didn't see anything in the JXA Cookbook (https://github.com/dtinth/JXA-Cookbook ) about this.

Upvotes: 13

Views: 2168

Answers (2)

stephancasas
stephancasas

Reputation: 2128

This question is old, but to any present or future visitors from Google, the correct function name to use is GURLGURL (no, I'm not joking). Your function signature should look something like this:

#!/usr/bin/env osascript -l JavaScript

function GURLGURL(url) {
  const App = Application.currentApplication();
  App.includeStandardAdditions = true;
  
  App.doShellScript(`echo ${url} > ~/Downloads/url-arg.txt`);
  return true;
}

I discovered this after reading through this archived developer document, and then probing my JXA script's applet process with the Console app. The message that gets dispatched is GURLGURL as in get URL.

Cheers to Apple for curating the worst developer experience for the best version of AppleScript.

Upvotes: 2

houthakker
houthakker

Reputation: 678

As you suggest, the trick (for the moment) seems to be to pass control immediately to a second (JavaScript for Automation) script in the same bundle.

on open location strURL
    run script (path to resource "jsHandler.scpt" in directory "Scripts") with parameters {{|URL|:strURL}}
end open location

Upvotes: 0

Related Questions