Skip to content

Scripts and the elc API ​

Open Scripts on a collection, folder or request and choose Pre-Request. Each phase inherits the nearest parent script by default. Its read-only editor shows its origin. Select Override to copy the effective code into an editable local script. Restore inheritance follows the parent again. These choices are separate for Pre-Request and Post-Request. Each phase runs at most one script.

The switch disables that phase for this item and its inheriting children. It does not fall back to a parent script. Children with their own overrides remain independent. An explicit empty override also suppresses the parent script. Save parent changes before sending child requests. Existing nonempty scripts are treated as overrides.

The caption uses the same origin display as Settings: On/Off and the source name. Click the source to open its script phase. The reset arrow beside Overridden here restores inheritance; Override creates a local editable copy.

Inherited script editors are dimmed and disabled until Override is selected. The switch shows execution state, including the inherited On/Off value; it does not indicate whether the source is editable. Resetting restores both the parent execution state and the disabled inherited editor.

Collections have no parent script and do not show an origin caption. Switching an inherited phase creates a local override with the effective code and chosen On/Off state. Save the item to keep activation and inheritance changes.

Selecting Scripts opens a collapsed request area to show the editor. In a request, drag the request/response divider down to give the script editor more space. Both script phases fill the available request area while keeping a minimum code height of 220 pixels. Smaller areas scroll without shrinking the code field below that minimum.

To hide Response entirely, hover or focus the request/response divider and select Collapse response area. The downward chevron collapses Response toward Console; the upward Expand response area control restores the previous split with enough space for the response heading and placeholder. The response is retained, and Console can remain open. You can also drag the divider to the bottom, or focus it and press End.

The active request uses its current draft. Parent scripts use saved collection and folder values. Save parent changes before sending. Syntax errors, rejected awaited calls, timeouts and cancellation stop the main request. No call is automatically replayed. HTTP calls already received by their target cannot be rolled back.

Cancel, closing the request and signing out stop its preparation. Each script has a separate JavaScript scope; temporary variables are shared between the two phases. Ordinary JavaScript loops, arrays, classes, promises and async/await are available. Named and dynamic imports are available for the bundled package catalog. Console output, timers, URL/URLSearchParams, TextEncoder/TextDecoder and selected crypto methods are documented in Script Web APIs. DOM and Node APIs remain unavailable.

Choose Post-Request to process the main response. Only the effective Post-Request script runs. HTTP error statuses (4xx/5xx) also run Post-Request. Transport failures do not. A Post-Request failure leaves the received response visible. Temporary variables survive from Pre-Request through Post-Request. Cancellation also stops Post-Request and its pending HTTP calls.

Obtain a token before sending ​

Define tokenUrl, clientId and clientSecret in your active environment. Prefer local secret values to credentials embedded in saved script text.

js
const response = await fetch(elc.variables.get('tokenUrl'), {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: 'grant_type=client_credentials'
    + '&client_id=' + encodeURIComponent(elc.variables.get('clientId'))
    + '&client_secret=' + encodeURIComponent(elc.variables.get('clientSecret')),
});
if (!response.ok) throw new Error('Token request failed');
const token = await response.json();
elc.request.headers.set('Authorization', 'Bearer ' + token.access_token);

Always await HTTP calls needed by the main request. Unfinished host calls are cancelled when their script completes. Check response.ok: HTTP error statuses produce responses rather than rejecting fetch.

elc.variables ​

Values resolve from temporary script values, then the selected environment, then globals. Existing local overrides take precedence over shared defaults. The environment selection and effective values are captured when sending starts.

get(name) ​

get(name: string): string | null | undefined reads an effective value. Missing names return undefined; variables without a value return null. Non-string names throw. It does not write or persist anything.

js
const tenant = elc.variables.get('tenantId');
if (!tenant) throw new Error('Set tenantId before sending');

set(name, value) ​

set(name: string, value: string): void temporarily overrides an existing variable for this send, available to subsequent scripts and placeholder substitution in the main request. Define the variable in Global variables or the selected environment first. Unknown names throw and stop the script; in Pre-Request the main request is not sent. Both arguments must be strings. It does not modify saved environments or local overrides. Temporary values are discarded after this execution.

js
elc.variables.set('tenantId', 'demo');

resolve(template) ​

resolve(template: string): string replaces complete placeholders using effective values. Missing or unset values throw; non-string templates throw. It does not mutate the template or variables.

js
const endpoint = elc.variables.resolve('https://example.test/{{tenantId}}/token');

elc.environment and elc.globals ​

Both objects are available in both phases. elc.environment accesses the selected inherited environment; elc.globals accesses global definitions. Reads prefer local overrides over shared defaults. Scope selection and values are captured at send time, with successful script writes carried into subsequent scripts.

get(name) ​

get(name: string): string | null | undefined reads from this scope only. Missing names return undefined; a defined variable without a value returns null. With no selected environment, all environment reads return undefined. Non-string names throw.

set(name, value) ​

set(name: string, value: string): void stages a local override for an existing variable in that scope. Define variables in Environments first. Unknown names, no selected environment, non-string arguments and values over 4096 characters throw. An empty string is a valid value. This API cannot create definitions, change shared defaults or remove an override.

Reads in the same script see the new value immediately. All scope writes from a script are persisted together after that script succeeds, on this device for the signed-in account. They are not broadcast to other clients. A failed script leaves its staged writes unapplied; writes from earlier successful scripts remain, even if a later script or the main HTTP call fails. Storage failure, changed variable definitions or a changed session reject the write. Concurrent sends use independent snapshots; the last successful write to a variable wins.

js
elc.globals.set('tenantId', 'demo');
const tenant = elc.globals.get('tenantId');

To capture a response ID, first define bookingId in the selected environment, then add this Post-Request script:

js
if (elc.response.ok) {
  const booking = await elc.response.json();
  elc.environment.set('bookingId', String(booking.id));
}

elc.response ​

Available only in Post-Request; undefined in Pre-Request. This read-only object represents the main request's response, not a script fetch response.

MemberTypeBehavior
statusnumberHTTP status code
statusTextstringHTTP status text
okbooleanTrue for status 200–299
durationMsnumberMain HTTP duration in milliseconds, excluding scripts
bytesnumberResponse body size reported by the transport
headers.get(name)(name: string): string or nullCase-insensitive first header lookup; missing headers return null; non-string names throw
text()(): Promise<string>Decoded body; await the result
json()(): Promise<unknown>Parsed body; invalid JSON rejects

Body reads can be repeated without consuming the body. The body is transferred only when read, so a large response can still be inspected by status or headers. Each body read must fit the 64 KiB serialized bridge-message limit. Oversized reads reject without removing the response from the UI. There is no streaming or binary response API. Assigning response properties throws.

elc.request ​

These Pre-Request changes affect only the outgoing execution. Saving the request does not save script-generated values back to its draft. In Post-Request the object describes the sent execution and is read-only; URL/method assignments and headers.set throw.

PropertyTypeBehavior
urlwritable stringURL template for the outgoing request; placeholders resolve after scripts
methodwritable stringGET, POST, PUT, PATCH, DELETE, HEAD or OPTIONS; normalized to uppercase
headersobjectHeader access through the methods below

Invalid types or unsupported methods fail preparation. Normal HTTP URL and header validation still applies before transport. Query parameters, raw/multipart body editing and execution settings are not exposed through this object.

js
elc.request.url = 'https://example.test/{{tenantId}}';
elc.request.method = 'GET';

headers.get(name) ​

get(name: string): string | undefined reads the first enabled custom header or the latest script override, case-insensitively. Missing headers return undefined; non-string names throw. It does not expose headers generated from Authorization settings during Pre-Request or automatic Content-Type settings. In Post-Request, headers added by Authorization preparation are included; transport-generated headers are not.

js
const existing = elc.request.headers.get('X-Tenant');

headers.set(name, value) ​

set(name: string, value: string): void replaces matching custom headers case-insensitively, enabling the resulting header. Both arguments must be strings; normal header validation and transport-managed header rules still apply. Setting Authorization explicitly overrides the request's Authorization configuration for this send. Automatic Content-Type retains its normal transport behavior.

js
elc.request.headers.set('X-Tenant', elc.variables.get('tenantId'));

elc.context ​

This object and its nested values are read-only and available in both phases. It has no methods or persistence effects. Assignments to frozen properties fail because scripts execute as strict JavaScript modules.

PropertyTypeMeaning
phasestringpre-request or post-request
collectionidentity or nullRoot collection; null for a request without a collection
foldersidentity arrayParent folders, outermost first
requestidentityRequest being sent
sourceidentityCollection, folder or request owning the current script

Each identity contains string properties id, name and kind.

js
elc.request.headers.set('X-Request-Name', elc.context.request.name);

fetch(url, options) ​

fetch(url: string | URL, options?: { method?: string, headers?: Record<string, string>, body?: string | URLSearchParams }): Promise<ScriptResponse> uses the main request's captured local/proxy route, TLS verification and redirect settings. It does not inherit its Authorization header, cookies or custom headers. Browser local calls remain subject to CORS; proxy target restrictions still apply. Only the listed options are supported. The default method is GET; bodies must be text or URLSearchParams (serialized as form data). Unsupported options, invalid requests and transport failures reject the call. There is no streaming, binary body or per-call signal API; request cancellation aborts pending calls.

Response memberTypeBehavior
statusnumberHTTP status code
statusTextstringHTTP status text
okbooleanTrue for status 200–299
headers.get(name)string or nullCase-insensitive lookup; missing headers return null; name must be a string
text()Promise of stringDecoded response body
json()Promise of unknownParsed body; invalid JSON rejects

The response is read-only. Body reads can be repeated without consuming the body.

js
const response = await fetch('https://example.test/status');
const mediaType = response.headers.get('content-type');
const body = await response.text();

Limits and errors ​

Each script has a 60-second deadline including HTTP waits, a 64 KiB source limit and a 32 MiB WebAssembly memory ceiling including interpreter overhead. The hierarchy supports at most 50 nodes. Bridge messages are limited to 64 KiB of UTF-8 JSON, including request/response metadata; this also limits the serialized initial variable snapshot, temporary values, local writes, response body reads and script fetch responses. There are at most 64 host calls per script, including initialization and finalization.

The complete Send operation (all Pre scripts, main HTTP call and all Post scripts) has a five-minute deadline. Each HTTP call has its own 60-second deadline; a script fetch also shares the remaining time of its script. Limits are fixed, not editable. Timeouts stop the execution and abort active HTTP calls. Cancellation has a separate message. No operation is automatically retried.

The error notification identifies the phase and script source. Open Script error details on the request to inspect the error name, message and stack when available. user-script.mjs refers to the source in your script editor. Syntax errors, rejected promises and explicit throws appear here. Thrown strings and null are supported; custom object fields beyond name/message/stack are not displayed. Each diagnostic field is truncated to 4096 characters. Details remain local to the request tab and clear when the next send starts; they are not saved, broadcast or added to the toast. Error text can contain values your script includes in its exceptions. The draft is preserved. Script preparation does not change the separate saved-body or main-request size limits described in the HTTP client guide.

Related: Web APIs · Package imports · Environments · HTTP client

The script editor marks unknown literal variable names in set() calls with an error underline and a red gutter marker, using the current item's environment and global definitions. This also applies to elc.globals.set() and elc.environment.set() in their respective scopes. get() permits missing names. Dynamic names and aliases are checked during execution rather than statically. Collection/folder scripts are checked in the edited item's context; a child request may select a different environment, so execution validation remains authoritative.

A little chemistry for your development workflow.