Tampermonkey® by Jan Biniok

GM_webRequest(rules, listener)

Note: this API is experimental and might change at any time. It is also not available anymore at Manifest v3 versions of Tampermonkey 5.2+ (Chrome and derivates).

GM_webRequest (re-)registers rules for web request manipulations and the listener of triggered rules. If you need to just register rules it's better to use @webRequest header. Note, webRequest proceeds only requests with types sub_frame, script, xhr and websocket.

Parameters:

  • rules - object[], array of rules with following properties:
    • selector - string|object, for which URLs the rule should be triggered, string value is shortening for { include: [selector] }, object properties:
      • include - string|string[], URLs, patterns, and regexpes for rule triggering;
      • match - string|string[], URLs and patterns for rule trigering;
      • exclude - string|string[], URLs, patterns, and regexpes for not triggering the rule;
    • action - string|object, what to do with the request, string value "cancel" is shortening for { cancel: true }, object properties:
      • cancel - boolean, whether to cancel the request;
      • redirect - string|object, redirect to some URL which must be included in any @match or @include header. When a string, redirects to the static URL. If object:
        • from - string, a regexp to extract some parts of the URL, e.g. "([^:]+)://match.me/(.*)";
        • to - string, pattern for substitution, e.g. "$1://redirected.to/$2";
  • listener - function, is called when the rule is triggered, cannot impact on the rule action, arguments:
    • info - string, type of action: "cancel", "redirect";
    • message - string, "ok" or "error";
    • details - object, info about the request and rule:
      • rule - object, the triggered rule;
      • url - string, URL of the request;
      • redirect_url - string, where the request was redirected;
      • description - string, error description.

Example

GM_webRequest([
    { selector: '*cancel.me/*', action: 'cancel' },
    { selector: { include: '*', exclude: 'http://exclude.me/*' }, action: { redirect: 'http://new_static.url' } },
    { selector: { match: '*://match.me/*' }, action: { redirect: { from: '([^:]+)://match.me/(.*)',  to: '$1://redirected.to/$2' } } }
], function(info, message, details) {
    console.log(info, message, details);
});