Skip to content

Access to Browser API webRequest #397

Open

Description

@vyach-vasiliev

Is it possible to make access to Browser API from the User-Script code? At least for Chrome-like browser.

Sometimes this really is really not enough and I do not want to write everytime extra extensions for the sake of a couple of lines of code.

Similar to:

    var filter = {urls: ["http://*/*", "https://*/*"], tabId: currentTabId };
    var opt_extraInfoSpec = ['blocking'];
    GM_webRequest.onBeforeRequest.addListener(
        callback, filter, opt_extraInfoSpec);

Activity

  1. tophf commented on May 7, 2017

    @tophf

    The thing is, blocking code is synchronous so it must be inside the background page of Tampermonkey and you surely understand it would be insane to allow arbitrary userscripts to run there.

    A viable solution might be declarative syntax e.g. provide an array of rules that specify what to do.

  2. tophf commented on May 7, 2017

    @tophf

    On the other hand, maybe Tampermonkey's sandbox can be applied to userscript code in the background page too...

  3. vyach-vasiliev commented on May 7, 2017

    @vyach-vasiliev
    Author

    @tophf I understand it and certainly agree with you what is required declarative syntax for rules. If I knew exactly how Tampermonkey works, I would try to implement it.

    Agree that this option would give a strong advantage before similar extensions?

  4. derjanb commented on May 8, 2017

    @derjanb
    Member

    Ok, I've created a preview that shows how GM_webRequest and @webRequest could possibly work.

    After downloading and drag and dropping it to the extension page you can install this script:

    // ==UserScript==
    // @name         GM_webRequest testing
    // @namespace    http://tampermonkey.net/
    // @version      0.1
    // @description  try to take over the world!
    // @author       You
    // @match        *://*/*
    // @include      http://new_static.url/*
    // @include      *//redirected.to/*
    // @grant        GM_webRequest
    // @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"}}}]
    // ==/UserScript==
    
    var currently_active_webrequest_rule = JSON.stringify(GM_info.script.webRequest); // == @webRequst header from above
    
    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);
    });
    
    /*
      Notes:
        Action:
          The final redirect: URL needs to be included into the scripts @match or @include header
        Selector:
          If just a string is given, it is interpreted as include: property.
          include:, exclude: and match: properties are supported and can have an array or a string value - the syntax equals @include, @match and @exclude
        @webRequest may have a human readable format in the future, but for now it's the stringified first argument of GM_webRequest and allow request 
          manipulation even if the script didn't run yet. The only downside atm is that you need to re-register the rules (which overrides all previous ones)
          in order to get manipulation events. GM_webRequest(currently_active_webrequest_rule, function...)
    */

    This all is not heavily tested so expect bugs here and there. :)

  5. jspenguin2017 commented on May 8, 2017

    @jspenguin2017

    @derjanb
    Thanks! This is going to help a lot!

    If I understood right, the callback function will only receive information about the WebRequest once it is done and is not able to manipulate it.
    In this case, I think being able to redirect to a generated string as the response content would be helpful.

    I know it is not a good idea to let random function to run in privileged extension context, but there can be times when that would be handy. What is your opinion on this? Should I just create another extension to do this or we can have a special header for it?
    The redirection and blocking that the design above allows can mostly be done by uBO, Adguard, or some other ad blockers, what they cannot do is run complex function to make dynamic decision.

    Also, as a side thought, shouldn't it be named TM_webRequest? Since this functionality is obviously not in Greasemonkey.

  6. vyach-vasiliev commented on May 9, 2017

    @vyach-vasiliev
    Author

    @derjanb
    Wow, thank you for such a prompt reply! ⚡

    I try to play with https://ssl.gstatic.com/gb/images/v1_b3735dd8.png, but not one of the rules does not work for me.
    What am I doing wrong?

    // ==UserScript==
    // @name         GM_webRequest testing
    // @namespace    http://tampermonkey.net/
    // @version      0.1
    // @description  try to take over the world!
    // @author       You
    // @match        *://*/*
    // @include      *gstatic.com/*
    // @include      https://google.com/*
    // @include      *//google.com/*
    // @grant        GM_webRequest
    // @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"}}}]
    // ==/UserScript==
    
    console.log("GM_webRequest start");
    
    var currently_active_webrequest_rule = JSON.stringify(GM_info.script.webRequest); // == @webRequst header from above
    
    GM_webRequest([
        //{ selector: '*gstatic.com/*', action: 'cancel' },
        { selector: { include: '*gstatic.com/*', exclude: 'http://exclude.me/*' }, action: { redirect: 'https://google.com/' } },
        //{ selector: { match: '*://*.gstatic.com*' }, action: { redirect: { from: '([^:]+)://(.+)gstatic.com/(.*)',  to: '$1://google.com/$2' } } }
    ], function(info, message, details) {
        console.log(info, message, details); // This also does not work
    });
  7. derjanb commented on May 9, 2017

    @derjanb
    Member

    Ah sorry, I forgot to add this information. Since intercepting requests makes things slower Tampermonkey only handles the following request types at the moment: 'sub_frame', 'script', 'xmlhttprequest' and 'websocket'.

    All other are considered to be replaceable by a userscript, even after they were loaded, but that's discussable.

  8. vyach-vasiliev commented on May 9, 2017

    @vyach-vasiliev
    Author

    Hm, can be done something like?

    /* here, any calculations of javasscript are not related to the page (setting vars, functions) */
    GM_webRequest([
            { selector: '*gstatic.com/*', action: 'replace' },
    ], function(info, message, details) {
            console.log(info, message, details);
    	details.url = details.url.replace('gstatic', 'gstatic-2');
    	return details;
    });
    input  >>> https://gstatic.com/index.php?foo=bar...
    output >>> https://gstatic-2.com/index.php?foo=bar...
    

    We change url or body of the request and query data from the site.
    With support for GET and POST requests.
    Of course, according to the rules, the script code will be executed once for each request.

  9. derjanb commented on May 10, 2017

    @derjanb
    Member

    We change url or body of the request and query data from the site.

    Atm only the URL via:

    { selector: { match: '*://match.me/*' }, action: { redirect: { from: '([^:]+)://match.me/(.*)',  to: '$1://redirected.to/$2' } } }

    With support for GET and POST requests.

    Shouldn't make a difference.

    details.url = details.url.replace('gstatic', 'gstatic-2');

    This can't work because all communication is asynchronous. This means when the request is inspected by the background page, then there is no synchronous way to contact the userscript to make a decision. That's why all rules need to be defined when the requests happens.

  10. vyach-vasiliev commented on May 10, 2017

    @vyach-vasiliev
    Author

    @derjanb
    You did not understand me. I meant, this scheme:

    1. Script installation
    2. Loading the script into the storage (function => toString)
    3. Reload background page and load Userscripts with GM_webRequest into array at background page.
    4. Start load request (and check rules Userscripts)
    5. Loading a script (string) from the storage(array) and executing into callback of webRequest

    So will it work?
    I don't understand webRequest's work well, but I'm afraid to give up hope for success 😃

  11. derjanb commented on May 10, 2017

    @derjanb
    Member

    Loading a script (string) from the storage(array) and executing into callback of webRequest

    The background page has all extension permissions. It's not possible to run foreign JavaScript code there without leaking these permissions. Sorry. That's why a defined rule set is needed to tell the background page what needs to be done with a request.

  12. vyach-vasiliev commented on May 10, 2017

    @vyach-vasiliev
    Author

    @derjanb
    Oh, thanks now everything is clear. But the parameters can still be read?
    There can be such a parser?

    var rules = [ 
            { event: 'request', key: 'url', action: replace: { from: '([^:]+)://match.me/(.*)', to: '$1://redirected.to/$2'}, },
    ];  // Execution in order
    GM_webRequest(rules, function(info, message, events) {
            console.log(info, message, events); // ex. events.request.url or events.response.body
    }); // Reload background page and load rules with GM_webRequest into array rules at background page.

    Help:

    • actions (action)
      • block
      • replace
    • events (event)
      • request
      • response
    • event keys (key)
      • url
      • header
      • body
    • types request (type, default - all types)
      • xmlhttprequest or fetch
      • window location
    • methods request (method, default - all methods)
      • POST
      • GET
      • etc

    UPDATE 03.06.17

  13. LennyPenny commented on Jun 2, 2017

    @LennyPenny

    I don't think only intercepting certain request types is a good idea. There might be instances where one wouldn't want some request to even be made in the first place. Also in general replacing things that already have been loaded by something that too has to first be loaded seems pretty slow as well.

    How about being able to configure which requests types will be intercepted?

  14. vyach-vasiliev commented on Jun 2, 2017

    @vyach-vasiliev
    Author

    @LennyPenny You mean, XHR and Location types of query handlers, as well as the query types like POST, GET and others?
    Give an example please, if it is not difficult for you 😃

  15. LennyPenny commented on Jun 2, 2017

    @LennyPenny

    I'm just responding to @derjanb and this #397 (comment)

  16. 48 remaining items

  17. 7nik commented on Aug 30, 2021

    @7nik

    @tylkomat, now webRequest is presented in both stable and beta versions.

  18. tylkomat commented on Aug 31, 2021

    @tylkomat

    @7nik thanks for the info. I didn't notice it was already inside.

    Canceling requests works. but redirect does not. Must the redirect url be from the same domain then the selector url?

  19. 7nik commented on Aug 31, 2021

    @7nik

    @tylkomat

    The final redirect: URL needs to be included into the scripts @match or @include header

  20. 7nik commented on Aug 31, 2021

    @7nik

    Here the docs I have for this function:

    GM.webRequest(rules, listener)

    (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.

    And here are some of my notes.

  21. QwertyChouskie-Asurion commented on Dec 14, 2021

    @QwertyChouskie-Asurion

    Ah sorry, I forgot to add this information. Since intercepting requests makes things slower Tampermonkey only handles the following request types at the moment: 'sub_frame', 'script', 'xmlhttprequest' and 'websocket'.

    All other are considered to be replaceable by a userscript, even after they were loaded, but that's discussable.

    Is this still the case? I need to modify an image that can be created and destroyed many times, and so far the only way I can find to do this is a redirect.

    I can do this using a separate browser extension (Request Interceptor), but really need to consolidate all changes I do to this webapp into one script.

  22. MikeDabrowski commented on Dec 14, 2021

    @MikeDabrowski

    I settled on overwriting fetch. I just assigned custom function to fetch, in it I did my intercept and at the end called original fetch. Maybe this will help someone.

  23. Nate-Wilkins commented on May 6, 2022

    @Nate-Wilkins

    I can't seem to do this at all in tampermonkey any more.
    I has a script that just overrode window.fetch on load but it appears to be reset after my script executes.

    Has anyone else figured out a way to do this?

    EDIT

    I solved it by overriding XMLHttpRequest (what is with this class name??).
    You can find the solution on StackOverflow here -> https://stackoverflow.com/questions/629671/how-can-i-intercept-xmlhttprequests-from-a-greasemonkey-script/72137265#72137265

    Also if this is considered a "Bug" in tampermonkey please please do not fix it unless there's a workaround.

  24. anonghuser commented on Nov 20, 2022

    @anonghuser

    oh wow how did i not find out about this sooner... can't even count how many times i've wanted it. but to be useful it will need more juice. if not arbitrary code execution, then at least regex search/replace in the response, and be applicable to the main html request too. this way we can really prepend a script tag to the html and solve the "guarantee to run before website scripts" hassles, among other things.

  25. anonghuser commented on Nov 20, 2022

    @anonghuser

    btw the api to manipulate most things is blocking but specifically for changing the body it is async, so maybe having user code for that part will be ok?

    edit: actually, reading more docs, it can be async for headers too.
    https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeSendHeaders

    To modify the headers asynchronously: pass "blocking" in extraInfoSpec, then in your event listener, return a Promise which is resolved with a BlockingResponse.

    edit 2: oh, you already knew, but it's ff only. i should've read the thread more carefully. sorry. though personally, this might be a good enough reason to switch to ff. amazing how chrome made no progress in the 5 years this has been open.

  26. damelco commented on Jan 31, 2023

    @damelco

    @derjanb
    so ... in 2023 whats "versions" of tampermonkey [still] contain this code?

    thanks!!

    -DJ

  27. damelco commented on Apr 9, 2023

    @damelco

    so far, script BLOCKING and REDIRECT seem very promising ...
    however sub-frame requests are ignored.
    have not tried xhr or websocket yet.

    thank you for where you have it so far!
    very cool.

    -DJ

  28. gear54rus commented on Mar 26, 2025

    @gear54rus

    @damelco @anonghuser and anyone else looking for programmable webRequest calls. I've began working on an extension that would do just that: Web Defuser. It allows one to define rules to intercept/modify/redirect any requests at any stage and aims to be more complete 'userscript' solution in the future.

    It already has the first release (which admittedly is lacking in the UI department) and I'd appreciate early adopter feedback!

  29. derjanb commented on Mar 26, 2025

    @derjanb
    Member

    You're using "blocking" web requests, just like Tampermonkey. So your solution has the same problem - it only works with Firefox.

  30. gear54rus commented on Mar 26, 2025

    @gear54rus

    You're using "blocking" web requests, just like Tampermonkey. So your solution has the same problem - it only works with Firefox.

    Definitely. I never claimed otherwise. The limitations of MV3 and Chrome are well known.

    However, Web Defuser can process all request types (including frame requests), has more expressive matching language (including interactive JS-based matching) and in general is trying to position itself as a solution on a different layer of request/response browser stack than TM (which this issue is about).

  31. influential-eliot commented on Mar 26, 2025

    @influential-eliot

    Us Firefox users will be more than happy to accept such brilliance, though, @gear54rus !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions