Tasker supports running JavaScript code in tasks or WebView scene elements. Most Tasker actions can be accessed direct from the JavaScript. JSON and XMLHTTPRequest are also directly available from the JavaScript code.
JavaScript can be embedded inline in tasks via the JavaScriptlet (direct specification of JavaScript to run) or JavaScript (load script from file) actions.
In both cases, the JavaScript executes in sequence with the other actions in the task and variables are transparently converted so pieces of JavaScript can be interwoven throughout the task.
<H1 onClick="setWifi( false )">ClickMeToTurnOffWifi</H1>
This allows a single WebView to present a complete user-interface.
In JavaScript(let)
actions, local variables (all lower case, e.g. %myvar) are directly accessible in the JavaScript without
the % sign (e.g. myvar). If the script changes the value, the new value is transparently
used by subsequent actions in the task.
The values of new (all lower case) variables declared in JavaScript (with the var
keyword) are also available to subsequent actions,
with the exception of those which are chain-declared e.g. var one = 'aval', two = 'bval';
In JavaScript embedded in HTML, the functions local and setLocal must be used to access variables local to the scene hosting the WebView.
If you're using a JavaScript
or JavaScriptlet
action and you disable Auto Exit, you have to set local variables with setLocal.
Local Tasker arrays are transparently available in Javascript(let)s and vice-versa. They are not available in WebViews.
Arrays which are not existing Tasker arrays must be declared in the JS as such i.e. in this case arr will not be visible to the remainder of the task:
var arr = getSomeArray();
Whereas in this case it will:
var arr = []; arr = getSomeArray();
Note that:
[]
while Tasker uses ()
So, for example, %arr(1)
(Tasker) is equivalent to arr[0]
(JavaScript).
JavaScript
actionMenu / More / Developer / Save JS Library Template
to get dummy
definitions for the built in functions. Include that file when developing on your PC.
To test in your JavaScript code whether you're on-device or not, use
var onAndroid = ( global( 'sdk' ) > 0 );
By using the JavaScript
action rather than JavaScriptlet
you can easily
access a file synced from PC to a file on the Android device.
If you specify a website URL as the content for your WebView, then testing the code on the target device is a simple matter of pushing the new version to your webserver and reloading the WebView on the device (see action Element Web Control)
Calls to most Tasker builtin functions (see below) are executed as normal single-action tasks and thus may be blocked by other executing tasks.
They execute at the priority of the task that executed the JavaScript plus two.
By default, the JavaScript(let)
action will end when the main execution
sequence is finished.
If you are using asynchronous code e.g. via setTimeout() or other callbacks, you should deselect Auto Exit. You are then responsible yourself for telling Tasker to continue the task by calling exit().
In any case, execution will stop when the timeout configured for the action is reached.
Several popular libraries are pre-selectable.
You may wish to download them manually to your local storage and change the http URL to a file URL so that Internet is not required to run your script.
Warning: library code will have access to local files, data providers etc. on the device
Important: if you are using your own libraries developed on Windows, you may need to convert CRLF style line endings to Unix style LF.
Tasker makes most of it's actions available via functions which can be called directly via name
in JavaScript(let)
actions and WebView elements.
Exceptions:
tk.flash('Woo!')
var ok = alarmVol( int level, bool display, bool sound )
Set the relevant system volume to level.
If display is true, the new level will be flashed up on-screen.
If sound is true, a tone will sound at the new level.
var ok = audioRecord( str destPath, str source, str codec, str format )
The JavaScript does not wait for the audio recording to complete.
See also: audioRecordStop().
var ok = audioRecordStop()
Stop recording previously initiated by audioRecord().
var ok = browseURL( str URL )
Open the default browser at the specifed URL.
var ok = button( str name )
Simulate a press of the named button.
name must be one of back, call, camera, endcall, menu, volup, voldown or search.
This function requires a rooted device.
var ok = call( str num, bool autoDial )
Make a phone call.
If autoDial is false, the phone app will be brought up with the number pre-inserted, if true the number will also be dialed.
var ok = callBlock( str numMatch, bool showInfo )
Block outgoing calls matching numMatch.
If showInfo is set, Tasker will flash a message when a call is blocked.
var ok = callDivert( str fromMatch, str to, bool showInfo )
Divert outgoing calls matching fromMatch to the number to.
If showInfo is set, Tasker will flash a message when a call is diverted.
var ok = callRevert( str numMatch )
Stop blocking or diverting outgoing calls previously specified with callBlock or callDivert.
var ok = carMode( bool onFlag )
Turn on or off Android Car Mode.
var ok = clearKey( str keyName )
Clear the passphrase for the specified keyName.
See Also: Encryption in the Userguide.
var ok = composeEmail( str to, str subject, str message )
Show an email composition dialog with any specified fields pre-filled.
The JavaScript does not wait for the email to be sent before continuing.
var ok = composeMMS( str to, str subject, str message, str attachmentPath )
Show an MMS composition dialog with any specified fields pre-filled.
The JavaScript does not wait for the MMS to be sent before continuing.
var ok = composeSMS( str to, str message )
Show an SMS composition dialog with any specified fields pre-filled.
The JavaScript does not wait for the SMS to be sent before continuing.
var result = convert( str val, str conversionType )
Convert from one type of value to another.
conversionType must be one of the string constants: byteToKbyte, byteToMbyte, byteToGbyte, datetimeToSec, secToDatetime, secToDatetimeM, secToDatetimeL, htmlToText, celsToFahr, fahrToCels, inchToCent, metreToFeet, feetToMetre, kgToPound, poundToKg, kmToMile, mileToKm, urlDecode, urlEncode, binToDec, decToBin, hexToDec, decToHex, base64encode base64decode, toMd5, toSha1, toLowerCase, toUpperCase, toUpperCaseFirst.
See also: action Variable Convert.
var ok = createDir( str dirPath, bool createParent, bool useRoot )
Create the named dirPath. If createParent is specified and any parent directory does not exist, it will also be created.
If useRoot is specified, the operation will be performed as the root user (where available).
var ok = createScene( str sceneName )
Create the named scene without displaying it.
var ok = cropImage( int fromLeftPercent, int fromRightPercent, int fromTopPercent, int fromBottomPercent )
Crop an image in Tasker's image buffer previously loaded via loadImage.
var ok = decryptDir( str path, str key, bool removeKey )
As decryptFile(), but decrypts each file in the specified directory in turn.
var ok = decryptFile( str path, str key, bool removeKey )
Decrypt the specified file using the encryption parameters specified in Menu / Prefs / Action
.
If removeKey is not set, the entered passphrase will be reapplied automatically to the next encryption/decryption operation with the specified keyName.
See Also: Encryption in the Userguide, Decrypt File action.
var ok = deleteDir( str dirPath, bool recurse, bool useRoot )
Delete the named dirPath. recurse must be specified if the directory is not empty.
If useRoot is specified, the operation will be performed as the root user (where available).
var ok = deleteFile( str filePath, int shredTimes, bool useRoot )
Delete the named filePath.
shredTimes has range 0-10.
If useRoot is specified, the operation will be performed as the root user (where available).
See also: action Delete File
var ok = destroyScene( str sceneName )
Hide the named scene if it's visible, then destroy it.
var ok = displayAutoBright( bool onFlag )
Whether the display brightness should automatically adjust to the ambient light or not.
var ok = displayRotate( bool onFlag )
Whether the display orientation should change based on the physical orientation of the device.
var ok = displayTimeout( int hours, int minutes, int seconds )
How long the period of no-activity should be before the display is turned off.
var ok = dpad( str direction, int noRepeats )
Simulate a movement or press of the hardware dpad (or trackball).
direction must be one of up, down, left, right or press.
This function requires a rooted device.
var ok = enableProfile( str name, boolean enable )
Enable or disable the named Tasker profile.
var ok = encryptDir( str path, str keyName, bool rememberKey, bool shredOriginal )
As encryptFile(), but encrypts each file in the specified directory in turn.
var ok = elemBackColour( str scene, str element, str startColour, str endColour )
Set the background colour of the specified scene element.
See also: action Element Back Colour.
var ok = elemBorder( str scene, str element, int width, str colour )
Set the border colour and width of the specified scene element.
var ok = elemPosition( str scene, str element, str orientation, int x, int y, int animMS )
Move an element within it's scene.
orientation must be one of port or land. animMS indicates the duration of the corresponding animation in MS. A zero-value indicates no animation.
See also: action Element Position.
var ok = elemText( str scene, str element, str position, str text )
Set the text of the specified scene element.
pos must be one of repl (replace existing text completely), start (insert before existing text) or end (append after existing text).
See also: action Element Text.
var ok = elemTextColour( str scene, str element, str colour )
Set the text colour of the specified scene element.
See also: action Element Text Colour.
var ok = elemTextSize( str scene, str element, int size )
Set the text size of the specified scene element.
See also: action Element Text Size.
var ok = elemVisibility( str scene, str element, boolean visible, int animationTimeMS )
Make the specified scene element visible or invisible.
See also: action Element Visibility.
var ok = endCall()
Terminate the current call (if there is one).
var ok = encryptFile( str path, str keyName, bool rememberKey, bool shredOriginal )
Encrypt the specified file using the encryption parameters specified in Menu / Prefs / Action
.
If rememberKey is set, the entered passphrase will be reapplied automatically to the next encryption/decryption operation with the specified keyName.
If shredOriginal is specified, the original file will be overwritten several times with random bits if encryption is successful.
See Also: Encryption in the Userguide, Encrypt File action.
var ok = enterKey( str title, str keyName, bool showOverKeyguard, bool confirm, str background, str layout, int timeoutSecs )
Show a dialog to enter the passphrase for the specified keyName. The JavaScript waits until the dialog has been dismissed or the timeout reached.
See Also: Encryption in the Userguide
bool ok = filterImage( str mode, int value )
Filter an image previously loaded into Tasker's image buffer via loadImage()
Possible values of mode are:
value should be 1-254.
bool ok = flipImage( bool horizontal )
Flip an image previously loaded into Tasker's image buffer via loadImage()
If horizontal is false, the image is flipped vertically.
exit()
Stop execution of the JavaScript.
flash( str message )
flashLong( str message )
var ok = getLocation( str source, bool keepTracking, int timeoutSecs )
Try to get a fix of the current device location.
source must be one of gps, net or any.
If keepTracking is set, the specified source(s) will be left tracking with the purpose of providing a much quicker fix next time the function is called.
Fix coordinates are stored in the global Tasker variables %LOC (GPS) and/or %LOCN (Net). The value can be retrieved with the global function. Several other parameters of the fix are also available, see Variables.
Example
var lastFix = global( 'LOC' );
if (
getLocation( 'gps' ) &&
( global( 'LOC' ) != lastFix )
) {
flash( "New fix: " + global( 'LOC' ) );
}
See also: action Get Location, function stopLocation.
str result = getVoice( str prompt, str languageModel, int timeout )
Get voice input and convert to text.
result is 'undefined' if the voice acquisition failed, otherwise it's an array of possible matching texts.
prompt is a label for the dialog that is shown during voice acquisition.
languageMode gives the speech recognition engine a clue as to the context of the speech. It must be one of web for 'web search' or free for 'free-form'.
goHome( int screenNum )
Go to the Android home screen. screenNum is not supported by all home screens.
var ok = haptics( bool onFlag )
Enable/disable system setting Haptic Feedback.
var ok = hideScene( str sceneName )
Hide the named scene if it's visible.
var value = global( str varName )
Retrieve the value of a Tasker global variable. Prefixing the name with % is optional.
Example:
flash( global( '%DogName' ) );
str files = listFiles( str dirPath, bool hiddenToo )
List all files in the specified dirPath.
files is a newline-separated list of subfiles.
If no files or found or an error occurs, the returned value will be undef
.
Example:
var files = listFiles( '/sdcard' ); var arr = files.split( '\n' ); flash( 'Found ' + arr.length + ' files' );
var ok = loadApp( str name, str data, bool excludeFromRecents )
Start up the named app.
Name can be a package name or app label, it's tested first against known package names. Note: app label could be localized to another language if the script is used in an exported app.
Data is in URI format and app-specific.
When excludeFromRecents is true, the app will not appear in the home screen 'recent applications' list.
var ok = loadImage( str uri )
Load an image into Tasker's internal image buffer.
The following uri formats are currently supported:
See also Load Image action.
var ok = lock( str title, str code, bool allowCancel, bool rememberCode, bool fullScreen, str background, str layout )
Show a lock screen, preventing user interaction with the covered part of the screen. The JavaScript waits until the code has been entered or the lock cancelled (see below).
var value = local( str varName )
Retrieve the value of a Tasker scene-local variable. The name should not be prefixed with %.
This function is only for use by JavaScript embedded in HTML and accessed via a WebView scene element.
var ok = mediaControl( str action )
Control media via simulation of hardware buttons.
Possible actions are next, pause, prev, toggle, stop or play.
var ok = micMute( bool shouldMute )
Mute or unmute the device's microphone (if present),
var ok = mobileData( bool set )
Enable or disable the system Mobile Data setting.
See also: action Mobile Data
var ok = musicBack( int seconds )
Skip back by seconds during playback of a music file previously started by musicPlay.
See also: musicSkip, musicStop
var ok = musicPlay( str path, int offsetSecs, bool loop, str stream )
Play a music file via Tasker's internal music player.
stream to which audio stream the music should be played
This function does not not wait for completion.
The last 3 arguments may be ommitted, in which case they default to 0, false and media respectively.
See also: musicStop, musicBack, musicSkip
var ok = musicSkip( int seconds )
Skip forwards by seconds during playback of a music file previously started by musicPlay.
See also: musicBack, musicStop
var ok = musicStop()
Stop playback of a music file previously started by musicPlay.
See also: musicBack, musicSkip
var ok = nightMode( bool onFlag )
Turn on or off Android Night Mode.
var ok = popup( str title, str text, bool showOverKeyguard, str background, str layout, int timeoutSecs )
Show a popup dialog. The JavaScript waits until the popup has been dismissed or the timeout reached.
var ok = performTask( str taskName, int priority, str parameterOne, str parameterTwo, str returnVariable, bool stop, bool variablePassthrough, str variablePassthroughList, bool resetReturnVariable )
Run the Tasker task taskName.
Note that the JavaScript does not wait for the task to complete.
bool active = profileActive( str profileName )
Whether the named Tasker profile is currently active. Returns false if the profile name is unknown.
bool ok = pulse( bool onFlag )
Enable or disable the Android Notification Pulse system setting.
var contents = readFile( str path )
Read the contents of a text file.
var ok = reboot( str type )
Reboot the device.
type is one of normal, recovery or bootloader. It can be ommitted and defaults to normal.
Requires a rooted device.
See also: function shutdown
var ok = resizeImage( int width, int height )
Scale the current image in Tasker's image buffer to the specified dimensions.
var ok = rotateImage( str dir, int degrees )
Rotate the current image in Tasker's image buffer.
dir must be one of left or right. degrees must be one of 45, 90, 135 or 180.
var ok = saveImage( str path, int qualityPercent, bool deleteFromMemoryAfter )
Save the current image in Tasker's image buffer to the specified file path.
Save Image action.
var ok = say( str text, str engine, str voice, str stream, int pitch, int speed )
Cause the device to say text out loud.
The script waits for the speech to be finished.
var ok = sendIntent( str action, str targetComp, str package, str class, str category, str data, str mimeType, str[] extras );
Send an intent. Intents are Android's high-level application interaction system.
Any parameter may be specified as undefined.
See also: action Send Intent.
var ok = sendSMS( str number, str text, boolean storeInMessagingApp );
Send an SMS.
See also: action Send SMS
var ok = setAirplaneMode( bool setOn )
Enable or disable Airplane Mode.
Get the current value with:
var enabled = global( 'AIR' );
See also: function setAirplaneRadios
var ok = setAirplaneRadios( str disableRadios )
Specify the radios which will be disabled when the device enters Airplane Mode.
disableRadios is a comma-separated list with radio names from the following set: cell, nfc, wifi, wimax, bt.
Get the current value with:
var radios = global( 'AIRR' );
See also: function setAirplaneMode
var ok = setAlarm( int hour, int min, str message, bool confirmFlag )
Create an alarm in the default alarm clock app.
confirmFlag specifies whether the app should confirm that the alarm has been set.
message is optional.
Requires Android version 2.3+.
var ok = setAutoSync( bool setOn )
Enable or disable the global auto-sync setting.
var ok = scanCard( str path )
Force the system to scan the external storage card for new/deleted media.
If path is defined, only that will be scanned.
See also: action Scan Card
var ok = setBT( bool setOn )
Enable or disable the Bluetooth radio (if present).
Test BT state with:
if ( global( 'BLUE' ) == "on" ) { doSomething(); }
var ok = setBTID( str toSet )
Set the bluetooth adapter ID (the name as seen by other devices).
setGlobal( str varName, str newValue )
Set the value of a Tasker global user variable. Prefixing varName with % is optional.
Arrays are not supported due to limitations of the Android JS interface.
var ok = setKey( str keyName, str passphrase )
Set the passphrase for the specified keyName.
See Also: Encryption in the Userguide.
setLocal( str varName, str newValue )
Set the value of a Tasker scene-local user variable. Variable names should not be prefixed with %.
This function is only for use by JavaScript embedded in HTML and accessed via a WebView scene element.
var ok = setClip( str text, bool appendFlag )
Set the global system clipboard.
Test the value with:
var clip = global( 'CLIP' );
var ok = settings( str screenName )
Show an Android System Settings screen.
screenName must be one of all, accessibility, addacount, airplanemode, apn, app, batteryinfo, appmanage bluetooth, date, deviceinfo, dictionary, display, inputmethod, internalstorage, locale, location, memorycard, networkoperator, powerusage, privacy, quicklaunch, security, mobiledata, search, sound, sync, wifi, wifiip or wireless.
var ok = setWallpaper( str path )
Set the system home screen wallpaper.
var ok = setWifi( bool setOn )
Enable or disable the Wifi radio (if present).
Test wifi state with:
if ( global( 'WIFI' ) == "on" ) { doSomething(); }
var output = shell( str command, bool asRoot, int timoutSecs )
Run the shell command command.
asRoot will only have effect if the device is rooted.
output is 'undefined' if the shell command failed. It's maximum size is restricted to around 750K.
var ok = showScene( str name, str displayAs, int hoffset, int voffset, bool showExitIcon, bool waitForExit )
Show the named scene, creating it first if necessary.
Overlay, OverBlocking, OverBlockFullDisplay, Dialog, DialogBlur, DialogDim,
ActivityFullWindow, ActivityFullDisplay, ActivityFullDisplayNoTitle
var ok = shutdown()
Shutdown the device.
Requires a rooted device.
See also: reboot
var ok = silentMode( str mode )
Set the system silent ('ringer') mode.
mode must be one of off, vibrate or on
var ok = sl4a( str scriptName, boolean inTerminal )
Run a previously created SL4A script.
var ok = soundEffects( bool setTo )
Setting the system Sound Effects setting (sound from clicking on buttons etc.
var ok = speakerPhone( bool setFlag )
Enable or disable the speakerphone function.
var ok = statusBar( bool expanded )
Expand or contract the system status bar.
var ok = stayOn( str mode )
Specify whether the device should remain on when power is connected.
Possible modes are never, ac, usb, any.
var ok = stopLocation()
Stop tracking a location provider. This is only relevant when a getLocation function has been previously called with the keepTracking parameter set.
var ok = systemLock()
Turn off the display and activate the keyguard.
Requires Tasker's Device Administrator to be enabled in Android settings.
bool running = taskRunning( str taskName )
Whether the named Tasker task is currently running. Returns false if the task name is unknown.
bool ok = takeCall();
Auto-accept an incoming call (if there is one).
bool ok = takePhoto( int camera, str fileName, str resolution, bool insertGallery )
Take a photo with the builtin camera.
See also: action Take Photo
var ok = type( str text, int repeatCount )
Simulate keyboard typing.
Requires a rooted device.
boolean ok = unzip( str zipPath, bool deleteZipAfter )
Unpack a Zip archive into the parent directory of the archive.
deleteZip causes the zip archive to be deleted after successful unpacking.
usbTether( bool set )
Enable or disable USB tethering.
See also: action USB Tether
vibrate( int durationMilliseconds )
Cause the device to vibrate for the specified time.
vibratePattern( str pattern )
Cause the device to vibrate following the specified pattern, which consists of a sequence of off then on millisecond durations e.g.
500,1000,750,1000
wait for 500ms, vibrates 1000ms, wait for 750ms, then vibrate for 1000ms.
wait( int durationMilliseconds )
Pause the script for the specified time.
Warning: may cause some preceeding functions not to complete in some situations. If in doubt, use JavaScript setTimeout() instead.
var ok = wifiTether( bool set )
Enable or disable Wifi tethering.
See also: action Wifi Tether
var ok = writeFile( str path, str text, bool append )
Write text to file path.
If append is specified, the text will be attached to the end of the existing file contents (if there are any).
boolean ok = zip( str path, int level, bool deleteOriginalAfter )
Zip a file or directory.
level is the desired compression level from 1-9, with 9 resulting in the smallest file and the longest compression time.
deleteOriginal causes path to be deleted if the zip operation is successful.
Relative file paths are relative to the root of the internal storage media.
So, for example, pics/me.jpg
might resolve
to /sdcard/pics/me.jpg
.