JavaScirpt - window.console proxy

297 views Asked by At

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;
         },
      });
1

There are 1 answers

0
Ludvík Prokopec On

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;
     },
  });