You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
@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?
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==varcurrently_active_webrequest_rule=JSON.stringify(GM_info.script.webRequest);// == @webRequst header from aboveGM_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. :)
Reacted by ฬะทçะรโลนร, tophf, jdoe1024, XuPengfei, Valeriy Manzhos, Peng Miao (mios), __, Drino955 and Eliot Cole
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.
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.
/* 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');returndetails;});
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.
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.
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.
@derjanb
Oh, thanks now everything is clear. But the parameters can still be read?
There can be such a parser?
varrules=[{event: 'request',key: 'url',action: replace: {from: '([^:]+)://match.me/(.*)',to: '$1://redirected.to/$2'},},];// Execution in orderGM_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.
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?
@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 😃
(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;
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.
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.
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.
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.
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?
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.
@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!
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).
Activity
tophf commentedon May 7, 2017
The thing is,
blockingcode 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.
tophf commentedon May 7, 2017
On the other hand, maybe Tampermonkey's sandbox can be applied to userscript code in the background page too...
vyach-vasiliev commentedon May 7, 2017
@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?
derjanb commentedon May 8, 2017
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:
This all is not heavily tested so expect bugs here and there. :)
jspenguin2017 commentedon May 8, 2017
@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.vyach-vasiliev commentedon May 9, 2017
@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?
derjanb commentedon May 9, 2017
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.
vyach-vasiliev commentedon May 9, 2017
Hm, can be done something like?
We change
urlorbodyof therequestand 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.
derjanb commentedon May 10, 2017
Atm only the URL via:
Shouldn't make a difference.
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.
vyach-vasiliev commentedon May 10, 2017
@derjanb
You did not understand me. I meant, this scheme:
So will it work?
I don't understand webRequest's work well, but I'm afraid to give up hope for success 😃
derjanb commentedon May 10, 2017
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.
vyach-vasiliev commentedon May 10, 2017
@derjanb
Oh, thanks now everything is clear. But the parameters can still be read?
There can be such a parser?
Help:
action)event)key)type, default - all types)method, default - all methods)UPDATE 03.06.17
LennyPenny commentedon Jun 2, 2017
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?
vyach-vasiliev commentedon Jun 2, 2017
@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 😃
LennyPenny commentedon Jun 2, 2017
I'm just responding to @derjanb and this #397 (comment)
48 remaining items
7nik commentedon Aug 30, 2021
@tylkomat, now webRequest is presented in both stable and beta versions.
tylkomat commentedon Aug 31, 2021
@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?
7nik commentedon Aug 31, 2021
@tylkomat
7nik commentedon Aug 31, 2021
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,xhrandwebsocket.Parameters
{ include: [selector] }, object properties:"cancel"is shortening for{ cancel: true }, object properties:"([^:]+)://match.me/(.*)";"$1://redirected.to/$2";"cancel","redirect";"ok"or"error";And here are some of my notes.
QwertyChouskie-Asurion commentedon Dec 14, 2021
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.
MikeDabrowski commentedon Dec 14, 2021
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.
Nate-Wilkins commentedon May 6, 2022
I can't seem to do this at all in tampermonkey any more.
I has a script that just overrode
window.fetchon 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.
anonghuser commentedon Nov 20, 2022
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.
anonghuser commentedon Nov 20, 2022
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
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.
damelco commentedon Jan 31, 2023
@derjanb
so ... in 2023 whats "versions" of tampermonkey [still] contain this code?
thanks!!
-DJ
damelco commentedon Apr 9, 2023
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
gear54rus commentedon Mar 26, 2025
@damelco @anonghuser and anyone else looking for programmable
webRequestcalls. 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!
derjanb commentedon Mar 26, 2025
You're using "blocking" web requests, just like Tampermonkey. So your solution has the same problem - it only works with Firefox.
gear54rus commentedon Mar 26, 2025
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).
influential-eliot commentedon Mar 26, 2025
Us Firefox users will be more than happy to accept such brilliance, though, @gear54rus !