_executeJS

Use pure JavaScript in your shortcuts


Description

There's a cool pattern I've seen in other shortcuts to offload more complex operations to javascript. It works by essentially making a simple webpage to run js code that does stuff, then outputs the result as text on the main document. The page source is base64 encoded to a URL in shortcuts, which can then be executed, and the contents retrieved as plain text.

I wrapped this functionality in a little utility shortcut.

Example: Here's a shortcut that makes use of it as an example: _xmlText2jsonText, which uses a javascript library (x2js) to convert xml to json so you can make Dictionaries out of xml data.

Usage: _executeJS takes a single Dictionary as input with the following keys:

{name}: {type} - description

'js':{Text} - The javascript code that will be executed. You must return something at the end of this text. (i.e. return "hello world";). Whatever you return will be the text output of this shortcut. If you return a javascript object or array, it will be serialized via JSON.stringify(), and you'll be able to convert to a Dictionary with the returned text. Otherwise, numbers and strings are left alone.

'libs':{Dictionary {'libName',{Text}}} - Optional javascript libraries that your code depends on. The idea here is to keep things organized. The libName doesn't really matter.. that's for you. The lib text content is any javascript that you want defined before your code runs. This can be anything from variable or function declarations, to copied minified libraries from npm or github.

'input': {Dictionary | Number | Quoted Text} - Optional data for your javascript to work with. A variable named 'input' will be provided to your script. If input is a dictionary, you'll be working with a javascript object in code. If input is a string, you must enclose in quotes when defined.

'debug': {Boolean} - Optional debug switch. When included and 'True', will popup a Quicklook of the script page source before executing. When I'm debugging, I turn this on and copy the page contents to my computer to actually work on the code instead of typing on my tiny phone.

Here’s the original Reddit post for this shortcut in case any of the comments help with usage: utility_shortcut_to_run_javascript


Latest Release Notes

1.0 - Oct. 21, 2018, 4:46 p.m.

Initial version