 (function () {
   const originalLog = console.log;
   const originalWarn = console.warn;
   const originalError = console.error;
   const originalDebug = console.debug;

   function log(type, args) {
     const loggedStr = Object.values(args).map((argValue) => {
       if (typeof argValue === "undefined") {
         return "undefined"
       } else if (typeof argValue === "object") {
         return JSON.stringify(argValue)
       } else {
         return argValue.toString()
       }
     }).join(", ").substring(0, 6000);
     originalLog(loggedStr)
     window.webkit.messageHandlers[type].postMessage(loggedStr);
   }


   console.log = function() {
     log("log", arguments);
     originalLog.apply(null, arguments);
   }

   console.warn = function() {
     log("warn", arguments);
     originalWarn.apply(null, arguments);
   }

   console.error = function() {
     log("error", arguments);
     originalError.apply(null, arguments);
   }

   console.debug = function() {
     log("debug", arguments);
     originalDebug.apply(null, arguments);
   }

   window.addEventListener("error", function (e) {
     log("exception", [
       `${e.message} at ${e.filename}:${e.lineno}:${e.colno}`,
     ]);
   });
 })();
