How To "Do Shell Script" in JXA

Hello chaps!

I’m currently playing around with JavaScript for Automation in Yosemite. Although, overall, I like it far better than AppleScript, there are certain things that seem to be very difficult for me.

All I’m trying to do is open a URL in my default browser. Here is what I have so far:


app = Application('System Events');
app.includeStandardAdditions = true;

app.doShellScript('open "http://google.com"');

Every time I run it, I get this error message: “Error on line 4: Error: A privilege violation occurred.”

Any idea what this means, or where I went wrong in my script?

Hi,

apart from the Yosemite stuff do shell script does not belong to System Events,
so try the runtime environment (current application) instead

app = Application.currentApplication()

Thanks StefanK - that worked! Here I go spending hours of time trying to figure it out, and it takes you all of what, 5 seconds?

Here’s the working script:


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

app.doShellScript('open "http://google.com"');

Cheers!

I just read the release notes (don’t know if they are public yet)
do you get it by searching for javascript automation yosemite on google

Btw, to open a URL you don’t need to use doShellScript, there is a direct method to open a URL:

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

app.openLocation("http://www.google.com");

Hello.

Does JXA work in Safari, or is it supposed to work from stand alone scripts ala AppleScripts? The Release notes are public by the way.

Edit

Does it work from within a webpage in Safari?

McUsrII: I assume you mean running the JOSA script inside a webpage?
No, it is standalone scripts (which can be saved as applications), just like Applescript.

Thanks.

I just thought it would be very useful, to be able use JXA from within webpages since then we’d have a nice frontend for generating reports and stuff. This would also simplify invocation of scripts from bookmarks/make it work again.