Closed Zezombye closed 3 weeks ago
Yes, CSP doesn't allow Tampermonkey to inject the script into the page, therefore it is executed in a FF-specific sandbox. This means you have to use exportFunction
to make the function available to the page.
https://github.com/Tampermonkey/tampermonkey/issues/1636#issuecomment-1781733309
My actual use case is overriding XMLHttpRequest.open() (since Twitter hasn't switched to fetch() after all, my script failing was due to the CSP change).
ChatGPT suggested me to use exportFunction then eval():
(function() {
// This function will override XMLHttpRequest.prototype.open
function overrideXHROpen() {
var open_prototype = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
console.log("test");
this.addEventListener('readystatechange', function(event) {
if (this.readyState === 4) {
//...
}
});
return open_prototype.apply(this, arguments);
};
}
// Use exportFunction to make the function available in the page's context
var overrideFunction = exportFunction(overrideXHROpen, window, { defineAs: 'overrideXHROpen' });
// Inject the function into the page context and execute it
window.eval('(' + overrideFunction + ')();');
})();
But eval() is also blocked by CSP.
It then suggested me to inject as a script element:
// Convert the function into a string and inject it as a script element
var script = document.createElement('script');
script.textContent = '(' + overrideXHROpen.toString() + ')();';
document.documentElement.appendChild(script);
// Remove the script after execution
script.parentNode.removeChild(script);
But same thing, CSP blocks inline scripts without nonce.
It then gave up and suggested to straight up modify the HTTP request (which btw would be a neat addition to TM).
Is it possible for TamperMonkey to modify CSP to be able to inject its own scripts?
Expected Behavior
Adding functions to unsafeWindow works, eg on youtube:
Actual Behavior
Running the following userscript gives:
Functions cannot be accessed in any way. (Probably a CSP issue?)
Tested while disabling all other scripts.
Specifications