replace-xhr-response

replace-xhr-response

The replace-xhr-response snippet replaces the response of a XHR request if the response text matches a given regular expression pattern.

Parameters

Name

Description

Mandatory

Default

search

String or regex pattern run against the stringified XHR response. If the value starts with jsonpath(, it is treated as a JSONPath query instead.

Yes

n.a.

replacement

Everything that matches the regex will be replaced with this. In JSONPath mode it is interpreted as a typed value instead of literal text.

No

empty string

needle

Replacement only happens if needle text is present in the response. Enclose in / for regex.

No

empty string

JSONPath mode

When search starts with jsonpath(, the response is parsed as JSON, the query is evaluated against it, every matching property is replaced, and the result is re-serialised. Use this when the value to change is a structured field rather than a text pattern — it avoids regex-matching a serialised payload, and lets you inject a real boolean or empty array instead of a string.

If the response is not valid JSON, or the query fails to evaluate, the rule is skipped and the response is left unchanged.

Filter examples

Filter

Result

replace-xhr-response '/ads:\\\\[(.*?)\\\\]/'

Removes anything like ads:[any-string] from every response body.

replace-xhr-response 'serve-ads:true' 'serve-ads:false'

Replaces the string in the response body.

replace-xhr-response 'serve-ads:true' 'serve-ads:false' example.com

Replaces only if the response contains "example.com".

replace-xhr-response 'jsonpath($.ads[*].enabled)' false

JSONPath mode. Sets enabled to the boolean false on every element of the ads array.

replace-xhr-response 'jsonpath($..trackingId)' null

Sets every trackingId property at any depth to null.

replace-xhr-response 'jsonpath($.slots)' emptyArray

Replaces the slots array with a real empty array.

Debugging

Message

When

Definition

XMLHttpRequest proxied

After wrapping XMLHttpRequest

XHR calls are intercepted.

Needle found in XHR response

Matching needle found

We will look for the search parameter next.

Needle not found in XHR response

Needle not found

Response will not be modified.

Search * replaced with replacement in XHR response

After replacement

The response was successfully replaced.

Invalid JSONPath query: <<search>>

Right after the snippet fires

The query could not be compiled, so the rule is not registered.

JSONPath match at [<<key>>], replaced with <<replacement>>

JSONPath mode, per matched property

A property matched the query and was replaced. One message per match.

JSONPath: skipping non-JSON response or evaluation error: <<message>>

Response could not be handled

The response was not valid JSON, or the query threw. The response is left untouched.