1

I'm trying to persist console.log, console.warn...

Is it possible to have a proxy on window.console?

I tried:

      new Proxy(window.console, {
         get(target, key) {
            const p = target[key];
            debugger;  // Never gets here!

            if (['error', 'info', 'log',  'warn'].includes(key)) {
               return async function(...args) {
                  p.apply(target, args);

                  // Persist log
                  debugger;
               }
            }

            return p;
         },
      });
user5507535
  • 1,580
  • 1
  • 18
  • 39
  • 1
    `// Never gets here!` Did you assign the proxy object back to `window.console`? Or how exactly are you accessing it? – Felix Kling Sep 23 '21 at 14:45
  • @FelixKling No, I didn't assign it back to `window.console`, assigning as you said works, but is this really necessary? I don't remember having to do this before while using proxy. – user5507535 Sep 23 '21 at 14:57
  • 1
    `new Proxy` returns a proxy. That's the object that contains the traps. You have to operate on *that* object. – Felix Kling Sep 23 '21 at 17:19

1 Answers1

2

You have to assign to the object you want to modify.

   window.console = new Proxy(window.console, {
     get(target, key) {
        const p = target[key];
        debugger;  // Never gets here!

        if (['error', 'info', 'log',  'warn'].includes(key)) {
           return async function(...args) {
              p.apply(target, args);

              // Persist log
              debugger;
           }
        }

        return p;
     },
  });