Scripts
A request can have a pre-request and a post-response JavaScript script, under Scripts beside Variables and Headers. They are off until you turn on Enable scripts for that tab. Opening a saved request that has scripts never enables them, and neither does importing a file, so you can read them first. A dot on Pre-request or Post-response shows which one has a script.
In the script editors, Enter at the end of a finished statement adds its semicolon (Settings → Code).
Scripts are plain JavaScript. They are not part of GraphQL or of any library: Wireglass gives each script one object of its own, gql, and that object is the script’s only way to reach the request, the response, the environment and the network. Postman’s pm scripts don’t run here as they are, because the names are different.
// pre-request: runs after {{variables}} are filled in, before the request is sentgql.request.headers['authorization'] = 'Bearer ' + gql.env.get('token');gql.request.variables.page = 2;const r = await gql.fetch('https://auth.example.test/token', { method: 'POST', body: '{}' });gql.env.set('token', r.json().token);
// post-response: runs once, after the first result (a subscription's first event)gql.env.set('userId', gql.response.data.me.id);console.log('stored', gql.env.get('userId'));The gql object
Section titled “The gql object”| Name | Pre-request | Post-response | What it is |
|---|---|---|---|
gql.env |
✓ | ✓ | Read and write environment variables |
gql.request |
✓ | The outgoing headers and variables, which the script may edit | |
gql.response |
✓ | The first result, read-only | |
gql.fetch |
✓ | ✓ | Make an HTTP request |
console |
✓ | ✓ | Write to Script output |
Reading gql.request in a post-response script, or gql.response in a pre-request script, throws an error. gql itself is frozen: you can’t add to it or replace its members.
gql.env
Section titled “gql.env”gql.env.get(name)returns the variable’s value as a string, orundefinedwhen there is no such variable. It sees the environment as it was when the script started, plus what the script itself has set since.gql.env.set(name, value)storesvalueas text: numbers and booleans become strings, so store an object withJSON.stringifyand read it back withJSON.parse.
set writes to the active environment, or to the globals when none is active. A new name is added as a normal variable; an existing one keeps its secret flag. The change shows up in Manage environments like a manual edit, and applies to the next request, not to this one’s endpoint or fields.
A name must start with a letter or _ and use only letters, digits, _, . and -, up to 100 characters. A write that is rejected doesn’t stop the script: it appears as a warning in Script output, such as Could not set "1st": ….
gql.request
Section titled “gql.request”gql.request.headers // { 'authorization': 'Bearer …', … }gql.request.variables // { page: 1, … }Both are copies of the request after {{variables}} are resolved, so a secret token shows here in clear. Change them in place, or assign new objects:
gql.request.headers['x-request-id'] = 'wg-' + Date.now();delete gql.request.headers['cookie'];gql.request.variables = { ...gql.request.variables, first: 50 };When the script ends, what it left is checked like anything typed by hand:
- Header values must be strings. Numbers and booleans are turned into strings; anything else (an object,
null) is an error. - Variables must be a JSON object, with no circular references.
- Headers and variables are each limited to 100,000 characters once serialised.
If the check fails, or the script throws, the request is sent unchanged, and the reason appears in Script output.
The script can’t change the endpoint or the query. To send to a different place, set a variable for the next run, and use it as {{name}} in the endpoint.
gql.response
Section titled “gql.response”{ status, // HTTP status, or 0 when the transport has none (WebSocket) durationMs, // time to the first result, or 0 when it isn't known headers, // the response headers, names in lower case, or {} over WebSocket data, // the result's data, or null errors, // the GraphQL errors array, or undefined extensions, // the result's extensions, or undefined}It is frozen all the way down, so it can’t be changed. A result with GraphQL errors still runs the script; check for them yourself:
if (gql.response.errors?.length) { console.warn('GraphQL errors:', gql.response.errors);} else { gql.env.set('cursor', gql.response.data.items.pageInfo.endCursor);}gql.response.headers holds the response’s HTTP headers for HTTP, SSE and multipart runs. Names are in lower case, so read them as gql.response.headers['x-request-id']; a header sent more than once is one value, joined with , . Over WebSocket it is an empty object, because the browser doesn’t show the handshake response to the extension.
const next = gql.response.headers['x-next-cursor'];if (next) gql.env.set('cursor', next);gql.fetch(url, options)
Section titled “gql.fetch(url, options)”Close to the browser’s fetch, but simpler:
const r = await gql.fetch('https://api.example.test/login', { method: 'POST', // GET by default headers: { 'content-type': 'application/json' }, body: JSON.stringify({ user: gql.env.get('user'), password: gql.env.get('password') }),});r.status // 200r.headers // { 'content-type': 'application/json', … }r.text // the body as a stringr.json() // the body parsed as JSON (throws if it isn't JSON)optionstakes onlymethod,headersandbody. The method is one ofGET,POST,PUT,PATCH,DELETE,HEADandOPTIONS;GETandHEADcan’t have a body.bodyis sent as text, so passJSON.stringify(…)for an object: an object passed as it is becomes"[object Object]".r.textis a property, not a method;r.json()is a method.- An HTTP error status such as 401 or 500 does not reject: check
r.status. The promise rejects when the URL isn’thttp(s), the method or a header is invalid, the request fails or takes more than 10 s, the response is over 5 MB, or the script has made 20 calls already. - Cookies are sent only when the tab’s Send cookies is on.
- Always
awaita call: when the script ends, any call still pending is cancelled.
The request is made by the extension, not by a web page, so the site’s CORS rules don’t stop it.
console
Section titled “console”console.log, debug, info, warn and error write a line to Script output. Strings are shown as they are and objects as JSON, so console.log('user', gql.response.data.me) prints the whole object on one line. A line is cut at 2,000 characters.
Pipeline
Section titled “Pipeline”{{variables}}are resolved in the endpoint, headers and variables.- The pre-request script runs, and may edit the resolved
gql.request.headersandgql.request.variables. If the Headers or Variables box isn’t valid JSON, the script is skipped and the usual error follows. - The request is validated and sent.
- When the first result arrives, the post-response script runs. It doesn’t hold up the response or a subscription’s later events. A request that fails before any result (a network error, for example) doesn’t run it.
History keeps the request as typed, with its placeholders, not as the script changed it.
Only one script runs at a time; if you start several runs quickly, their scripts wait in turn.
Output
Section titled “Output”Script output appears in a Script output block above the response, with each line marked pre-request or post-response. It shows the script’s console lines, rejected gql.env.set writes, and the script’s error, with its line number when there is one:
TypeError: Cannot read properties of undefined (reading 'id') (line 3)A script that throws or times out never blocks the run or hides the response.
What else a script can use
Section titled “What else a script can use”A script runs as the body of an async function, so await works at the top level, and return ends the script early. The standard JavaScript built-ins are there: JSON, Math, Date, Promise, URL, TextEncoder, atob, btoa and so on.
These names are undefined inside a script: window, self, globalThis, document, parent, top, chrome, fetch, XMLHttpRequest, WebSocket, EventSource, Worker, SharedWorker, importScripts, postMessage, navigator, localStorage, sessionStorage, indexedDB, caches, setTimeout, setInterval, setImmediate and queueMicrotask. Without timers, a script can’t wait or poll; it ends when its last await is done.
Recipes
Section titled “Recipes”Log in once, reuse the token
Section titled “Log in once, reuse the token”// pre-requestif (!gql.env.get('token')) { const r = await gql.fetch(gql.env.get('authUrl'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ clientId: gql.env.get('clientId'), secret: gql.env.get('clientSecret') }), }); if (r.status !== 200) throw new Error('Login failed: ' + r.status + ' ' + r.text); gql.env.set('token', r.json().access_token);}gql.request.headers['authorization'] = 'Bearer ' + gql.env.get('token');Because the header is set by the script, this works on the first run too, although gql.env.set only reaches {{token}} from the next request on.
Page through results
Section titled “Page through results”// pre-requestgql.request.variables.after = gql.env.get('cursor') ?? null;
// post-responseconst page = gql.response.data.items.pageInfo;gql.env.set('cursor', page.hasNextPage ? page.endCursor : '');console.log(page.hasNextPage ? 'next page ready' : 'last page');Check a response
Section titled “Check a response”// post-responseconst user = gql.response.data?.me;if (!user) throw new Error('No user in the response');if (gql.response.durationMs > 1000) console.warn('slow:', gql.response.durationMs, 'ms');console.info('ok:', user.id);Limits
Section titled “Limits”- 5 s per script. A runaway loop is stopped and the next run works.
- 50,000 characters of source and 200 output lines.
- At most 20
gql.fetchcalls per script, each limited to 10 s,http(s)URLs only, a 5 MB response, and no cookies unless the tab’s Send cookies is on. - Only
gql,consoleand the standard JavaScript built-ins exist: nowindow, DOM,chrome, storage or timers.
Safety
Section titled “Safety”Scripts run in a Worker inside a sandboxed extension page with its own opaque origin, whose content security policy forbids every network request, so gql.fetch is the only way out. Scripts can’t read other tabs, collections, history or chrome.*. A script that runs too long is stopped by throwing the whole sandbox away.
Saving a request saves its scripts, and exporting a collection writes them as written, so remove any secrets first.
© 2026 Melliforge. All rights reserved.