I'm trying to write a library that intercepts all XMLHttpRequest calls and do something before eventually sending out the request, by overriding its prototype, for example:
var original_open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
// my own override logic here before running the original function
original_open.apply(this, arguments);
};
The problem is, I want to guarantee that when someone uses this library, it is impossible for any other code on the web page to re-override this effect.
Because otherwise, the website using this library can dynamically load another piece of JS code which simply overrides the XMLHttpRequest.prototype.open again, and the whole purpose of this library is to disallow that.
I thought about freezing the prototype using Object.freeze() right after the override, so that no other code can override my own override. The code would look something like this:
var original_open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
// my own override logic here before running the original function
original_open.apply(this, arguments);
};
Object.freeze(XMLHttpRequest.prototype);
My expectation is that, if another piece of code on the same page tries to re-override my own override, it will fail because the prototype has been frozen.
My question:
- Is this the correct solution for this problem?
- Is this truly secure? (No loopholes)?