API reference · GAP 4.6
Everything a script
can call.
Every function is a global: a script calls tap(…), not gap.tap(…). Scripts are modern JavaScript (ES2023) running in GAP's engine on the device.
Conventions
- Images are integer handles, and
0means “no image”.openImage()returns0for a missing file. Every handle you get must be passed toreleaseImage()— they are native memory, not garbage-collected. - Some image functions change the image you pass in instead of returning a new one. They are marked in place below.
- Coordinates are screen pixels, the same space for screenshots and touches. Fractions are rounded.
duringis a wait after the action, giving the app time to react — not how long a finger is held.- Calls marked newer are not in GAP 3.3, the current stable release, so check first:
if (typeof gapPerf === 'function') … - Calls marked opt-in do nothing until the user switches them on for that script.
start() and stop()
A script defines two globals. The floating bar's Play calls start(settings) through the settings page, and Stop calls stop(). start() usually loops; stop() runs on another thread while it does, so it only needs to clear a flag the loop checks.
var running = false;
function start(settings = {}) {
running = true;
while (running) {
// look, decide, act
sleep(500);
}
}
function stop() {
running = false;
}Pause needs nothing from the script: GAP freezes it inside sleep() and inside every touch call (not keycode() or typing()), and it continues from the same spot on resume. After a Stop, new touches from that run are dropped; a drag already in progress can still finish its moveTo() and tapUp().
Optional hooks: define onPause() and onResume() to be called around a pause, and reportIssue(reason, arg) to be called when the user holds the bar's Log button to report a problem. A script can also name itself with const GAP_SCRIPT_ID = '…'.
Screen
| Call | Returns | What it does |
|---|---|---|
| getScreenSize() | {width, height} | The screen size right now, following rotation. |
| getVirtualButtonHeight() | number | Height of the navigation bar, 0 when there is none. |
| getScreenshot() | image | The whole screen, in BGRA. About a millisecond on the fast capture path. |
| getScreenshotModify(cropX, cropY, cropW, cropH, resizeW, resizeH, quality) | image | A region of the screen, optionally resized. Crop first, then resize (0 = no resize); a quality of 1–99 adds a JPEG round-trip, 100 leaves it out. |
| getColor(x, y) | {r, g, b, a} | The colour of one pixel, from a fresh capture. Nothing to release. |
| getColors(points) | [{r, g, b, a}] | Several pixels from one capture. points is [{x, y}]. |
Touch and keys
| Call | Returns | What it does |
|---|---|---|
| tap(x, y, during, holdMs) | — | Press, hold holdMs (default 40, up to 5000), release, then wait during ms. holdMs is newer. |
| tapDown(x, y, during) | — | Put a finger down. |
| moveTo(x, y, during, wait) | — | Move the finger that is down. With wait true it returns only once the app has taken the move, so a long drag on a busy app loses nothing. |
| tapUp(x, y, during) | — | Lift the finger. |
| swipe(x1, y1, x2, y2, during) | — | A swipe: down, ten moves, up. |
| keycode(label, during) | — | Press a key: 'HOME', 'BACK', 'KEYCODE_ENTER', or a number. |
| typing(words, during) | — | Type text into whatever has focus. Characters the keyboard map can't produce are skipped. |
| readTouch(timeoutMs) | {x, y, down} | null | Wait for the user's next touch, in screen pixels. Up to 120 s; null on timeout. |
| touchDevices() | [{path, xMax, yMax}] | The touchscreens the device reports. |
Apps and device
Always available, with no shell needed.
| Call | Returns | What it does |
|---|---|---|
| launchApp(package, activity) | boolean | Open an app, by its launcher entry unless you name an activity. Opening one that is already open doesn't stack a second copy. |
| stopApp(package) | boolean | Force-stop an app. |
| isInstalled(package) | boolean | Whether an app is installed. |
| foregroundApp() | {package, activity} | null | The app in front. |
| deviceInfo() | object | null | {model, manufacturer, device, androidRelease, fingerprint, emulator, density, rooted}. density and rooted are newer. |
| dumpUi() | string | The window hierarchy as XML, "" when it can't be read. Handy for reading text and finding views by id. |
| getDeviceId() | string | Twelve hex digits naming this device, stable across reboots, different per emulator instance. |
| getDeviceName() | string | The device's name, as set in GAP's Settings; if unset, its model and the start of its id. |
Image processing
OpenCV underneath. Colour bounds are per channel in B, G, R, A order.
| Call | Returns | What it does |
|---|---|---|
| clone(img) | image | A copy. |
| cropImage(img, x, y, width, height) | image | A rectangle of it. Clamped to the image; entirely outside returns 0. |
| resizeImage(img, width, height) | image | Scaled. |
| bgrToGray(img) | image | Greyscale. |
| absDiff(a, b) | image | Per-pixel difference — what changed between two frames. |
| inRange(img, minB, minG, minR, minA, maxB, maxG, maxR, maxA) | image (mask) | White where a pixel's colour is inside the bounds. |
| outRange(img, minB, minG, minR, minA, maxB, maxG, maxR, maxA) | image (mask) | White where it is outside. |
| cloneWithMask(img, mask) | image | Only the masked pixels. |
| canny(img, t1, t2, apertureSize) | image | Edges. |
| findContours(edges, minArea, maxArea) | [{x, y, width, height, area}] | Outlines found in an edge image, as boxes. maxArea 0 = no upper limit. |
| houghCircles(img, method, dp, minDist, p1, p2, minR, maxR) | [{x, y, radius}] | Circles. |
| smooth(img, type, size)in place | — | Blur: 1 box, 2 Gaussian, 3 median, 4 bilateral. |
| convertColor(img, code)in place | — | Convert colour space with an OpenCV code. |
| threshold(img, thr, maxThr, code)in place | — | Threshold. |
| eroid(img, width, height, x, y)in place | — | Erode (the name is the original API's). |
| dilate(img, width, height, x, y)in place | — | Dilate. |
| drawCircle(img, x, y, radius, r, g, b, a)in place | — | Draw a circle, for debug pictures. |
Matching
| Call | Returns | What it does |
|---|---|---|
| findImage(img, template) | {x, y, score} | Where the template best matches, with a score from 0 to 1. x, y is the top-left corner. A template bigger than the image gives {x: -1, y: -1, score: -1}. |
| findImages(img, template, scoreLimit, resultCountLimit, withoutOverlap) | [{x, y, score}] | Every match above a score. |
| getIdentityScore(a, b) | number | How alike two pictures are, resizing b to a first — “is this the same screen?”. |
Single-colour templates are handled: they are matched a different way so a score of 1.0 still means a perfect match.
Image files
| Call | Returns | What it does |
|---|---|---|
| openImage(path) | image | Load a PNG or JPEG. 0 when the file is missing. |
| saveImage(img, path) | — | Save, creating folders. .jpg drops transparency. |
| getImageSize(img) | {width, height} | |
| getImageColor(img, x, y) | {r, g, b, a} | A pixel of an image you hold. Outside the image gives zeros. |
| getImageColors(img, points) | [{r, g, b, a}] | Several at once. |
| releaseImage(img) | — | Free it. Using it afterwards throws. |
| getImageFromBase64(text) | image | Decode, data: prefix allowed. |
| getBase64FromImage(img) | string | PNG as base64. |
| getImageFromURL("env:KEY")opt-in | image | Download an image from a URL the user configured; 0 if that fails or is not allowed. See network. |
Timing and paths
| Call | Returns | What it does |
|---|---|---|
| sleep(ms) | — | Wait. Stop, Close and Pause all take effect during it. There is no setTimeout: scripts are loops around sleep(). |
| getScriptPath() | string | This script's own folder — use it for images/ and anything shipped with the script. |
| getStoragePath() | string | GAP's folder, …/Download/GeneralAutomationPlatform. |
| getDevicePath() | string | A folder for this device alone, for output. Use it when several emulators share storage. |
Files
| Call | Returns | What it does |
|---|---|---|
| readFile(path) | string | "" when it can't be read. |
| writeFile(path, text) | — | Creates folders as needed. |
| makeDirs(path) | boolean | Like mkdir -p. |
| listDir(path) | [string] | Names, sorted. A missing folder lists empty. |
| copyFile(from, to) | boolean | Overwrites. |
| removeFile(path, recursive) | boolean | Folders only with recursive. |
Shell: execute()
When no named call does what you need, execute() runs any shell command with the same access adb shell has — am, pm, settings, input, and the rest.
| Call | Returns | What it does |
|---|---|---|
| execute(command)opt-in | string | Runs command and returns its output (stdout and stderr together). "" while the switch is off. |
Off until the user allows it: tap the script's card in the Library, tap Settings to open its Script env screen, and turn on Allow shell commands (GAP asks to confirm). On GAP 4.4 and earlier, Script env is the sliders button on the card instead. Scripts signed for GAP Companion always have it. The switch applies at once. Write scripts to carry on without it, and prefer the named calls above — they are faster and always available. The Playground example uses it this way to open a web page.
// Open a web page — something no named call does.
var out = execute('am start -a android.intent.action.VIEW -d "https://example.com"');
if (out === '') {
console.log('Shell is off: open the page yourself, or allow shell commands');
}Overlay, log and events
| Call | Returns | What it does |
|---|---|---|
| console.log / info / warn / error / debug | — | To the log panel, the settings page's onLog(), logcat (gap.script) and the log file in logs/. Objects are printed as JSON. |
| showBanner(message, duration, plays) | — | A line on the banner beside the floating bar. plays 0 = for the whole run. Also takes {message, duration, plays}. |
| setReadTop(y) | — | The top-most screen row the script reads, so GAP keeps its status line above it. Negative withdraws it. |
| pauseScript() | — | Pause this run, as if Pause were pressed. The user resumes it. |
| emitEvent(name, data) | — | Broadcast one of your own events to tools on a computer — to start a screen recording, say. Up to 50 a second, 16 KB each. |
| emitTrace(kind, data) | — | Live debug data for a developer tool. |
| traceAttached() | boolean | Whether such a tool is connected; check before building anything expensive. |
| traceWantFrame() · traceFrameId() | — · number | Send the next capture to the tool; the id sent for the latest capture, or 0 if it was not sent. |
Settings and network
A script never names a URL. It ships gap-env.json listing the values it wants; the user fills them in from a button on its Library card, and must switch on Use environment variables and, for requests, Allow network requests. Requests then say "env:KEY", and GAP sends them to the URL the user typed.
| Call | Returns | What it does |
|---|---|---|
| getEnv(key)opt-in | string | number | boolean | undefined | The user's value, else the default. undefined while variables are off. |
| httpClient(method, "env:KEY", body, headers)opt-in | string | A request that waits for the answer. Error bodies are returned too; "" when refused or failed. |
| httpRequest(method, "env:KEY", body, headers)opt-in | number | A request that returns at once with an id; the answer arrives as a network event. |
| addNetworkListener(fn) · removeNetworkListener(fn) | — | fn({id, type, status, body, error, …}) for each step: queued, sent, then done, failed or refused. |
Limits: one request at a time, at least a second apart, 30 a minute per key, bodies up to 1 MiB. Settings pages can't use the network at all.
Script control
| Call | Returns | What it does |
|---|---|---|
| importJS(library) | — | Load another file: an absolute path, or a name from libs/ or scripts/. |
| runScript(code) | — | Evaluate code in the script's global scope. |
| encrypt(code) · runEncryptedScript(text) | string · — | Ship closed-source code: encrypt once, run the result. |
Restarts and speed
For long runs that slow down over hours. Both take and return JSON text.
| Call | Returns | What it does |
|---|---|---|
| gapPerf(options)newer | JSON | The run's capture rate and capture time against how fast the device was just after it started, and whether that counts as slow. |
| gapRestartDevice(options)neweropt-in | JSON | Restart the device. Needs shell access, and GAP Companion linked to start the run again afterwards. |
Settings page bridge
A script's index.html runs in GAP's floating window, offline. It talks to the script through JavaScriptInterface, and GAP calls back into it.
| In index.html | Kind | What it does |
|---|---|---|
| onEvent(type) | you define | A floating-bar button was pressed: OnPlayClick, OnPauseClick (the Stop button), OnCloseClick, OnSettingClick, OnLogClick, OnMenuClick. |
| onLog(message) | you define | Every console line from the script. |
| onGapState(json) | you define | Quick Bar page only: the run's state, {active, paused, visible, stripHeight}. |
| onGapMessage(topic) | you define | A nudge from the script's other page (settings ↔ Quick Bar). |
| JavaScriptInterface.runScript(code) | call | Run code in index.js, e.g. 'start(' + JSON.stringify(settings) + ');'. |
| JavaScriptInterface.runScriptCallback(code, fnName) | call | Run it and call the page's fnName(result) with the answer. |
| JavaScriptInterface.showMenu() · hideMenu() | call | Show or hide the floating bar. showMenu() also closes the settings panel, so an OnPlayClick handler calls it to get out of the way. |
| JavaScriptInterface.setClipboard(text) · getClipboard() | call | The system clipboard. |
| JavaScriptInterface.broadcast(topic) | call | Nudge the script's other page. |
| JavaScriptInterface.setVersion(version) | call | The version on the bar's first chip (or define a VERSION global). |
| JavaScriptInterface.setQuickBarExpanded(on) · setQuickBarHotspot(l, t, w, h) | call | Quick Bar layout. |
| JavaScriptInterface.stopScript() · interruptScript() | call | Stop the run: politely, through the script's stop(), or at once, even mid-loop. |
| JavaScriptInterface.log(message) | call | Write a line to the script's log. |
| JavaScriptInterface.getScriptId() · isServiceConnected() | call | This script's id; whether GAP's engine is reachable. |
| JavaScriptInterface.close() | call | Close the floating window. |
| localStorage | web API | Where settings are kept between runs. |
Files in a script folder
| File | Needed | What it does |
|---|---|---|
| index.js | yes | The script. |
| index.html | yes | Its settings page, which also connects Play and Stop. |
| images/ | no | Templates for findImage(). |
| quickbar.html | no | A strip of the script's own buttons beside the floating bar. |
| floating-bar.json | no | Sizes, colours and icons for the floating bar. |
| gap-env.json | no | The values the script asks the user for (URLs, keys) — see network. |
| gap-backup.json | no | {"v": 1, "keys": [...]}: which localStorage keys get Back up / Restore settings on the card. |
The language
QuickJS-ng with ES2023: class with private fields, async/await, generators, optional chaining, ??, destructuring, template literals, BigInt, Proxy. Files are classic scripts, so function start(){} lands on the global object; name a file .mjs for module semantics. There is no setTimeout or setInterval.
Nothing matches that filter.