3

How do you start an application in JavaScript via osascript?

I have been playing around with some of the examples, which can be found on the Internet and I can get them to work, but if an application targeted for automation is not already started I get the following error:

2015-04-02 10:43:34.749 js.sh[3434:57612] warning: failed to get scripting definition from /Applications/Safari.app; it may not be scriptable.

If Safari is already open, the following example works like a charm.

#!/usr/bin/osascript -l JavaScript

var Safari = new Application("/Applications/Safari.app");

Safari.activate;

window = Safari.windows[0];

tab = Safari.Tab({url:"http://www.dr.dk"});
window.tabs.push(tab);
window.currentTab = tab;

I thought the activate method was the one, but it seems I have overlooked something.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jonasbn
  • 183
  • 4
  • 11
  • JXA should automatically launch the targeted application if it isn't already running. OTOH, JXA, like Scripting Bridge before it, is riddled with design flaws and implementation bugs, so don't be overly surprised if/when it does screw up. The only supported option that works right is AppleScript. – foo Apr 02 '15 at 13:14
  • BTW, `Safari.activate` should read `Safari.activate()` as JavaScript's function objects don't do anything unless you call them. However, all that'll do bring Safari to the front. Sending Apple events WON'T launch an application: the Apple Event Manager's job is to talk to _existing_ processes, not start new ones (that's LaunchServices' responsibility). If the app isn't already running, it's up to the client (e.g. AppleScript) to launch it via `-[NSWorkspace launchApplicationAtURL:options:configuration:error:]` _before_ sending AEs to it. AS does it right; if JXA doesn't, that's cos it's junk. – foo Apr 02 '15 at 13:42

1 Answers1

3

Your script worked just fine on my machine, and Safari launched. To bring the application to the front, you need to change this line:

Safari.activate;

to this:

Safari.activate();

You must call the activate command as a function (using parentheses).

syntaxera
  • 254
  • 3
  • 5