Hooking javascript object literal constructors to modify objects created in inaccessible contexts

66 Views Asked by At

I'm attempting to modify an object present in code that I do not control and cannot directly alter. Ideally, I'd like to do this from a bookmarklet, but the extra permissions of a userscript are also a usable context.

The code I'm attempting to hook looks like this:

(() => {
  var target = { nestedsubobject: { foo: 'value' } };
  // does some stuff with target
})();

I'd like to intercept the object literal assigned to target and modify the value of foo, before the IIFE uses it further.

So far everything I've tried that doesn't work:

  • Prototypes appear unrelated to this problem. While I can override the global object prototype, this gives me no way to actually listen for objects created using that prototype.
    • Using Object.defineProperty on Object.prototype to define nestedsubobject or foo with writable: false or get() results in the client code throwing TypeError: can't redefine non-configurable property (...) when constructing the target object. Configuring with value just results in the property being present in the new object and thus ignored in the prototype object.
  • Constructors are bypassed with object literals. While I can override the global object constructor (as in Override JavaScript global native Object() constructor), the literal syntax doesn't appear to use that constructor.

Additionally, I can't alter the code directly (e.g. intercepting and rewriting the network request for it) because I expect that it may be obfuscated in the future. I'd like to directly hook object creation to make my userscript much more durable.

This is running in a browser context.

0

There are 0 best solutions below