consoleLogCapture.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const { ipcRenderer } = require('electron');
  2. const extractLineNumberFromStack = function(stack) {
  3. // / <summary>
  4. // / Get the line/filename detail from a Webkit stack trace. See http://stackoverflow.com/a/3806596/1037948
  5. // / </summary>
  6. // / <param name="stack" type="String">the stack string</param>
  7. let line = stack.split('\n')[2];
  8. // fix for various display text
  9. if (line) {
  10. line =
  11. line.indexOf(' (') >= 0
  12. ? line.split(' (')[1].substring(0, line.length - 1)
  13. : line.split('at ')[1];
  14. return line;
  15. }
  16. };
  17. module.exports = function(windowId) {
  18. if (typeof window === 'undefined') {
  19. return;
  20. }
  21. windowId = windowId || window.location.url;
  22. const console = window.console;
  23. // send console logging to IPC backend
  24. ['trace', 'debug', 'info', 'warn', 'error', 'log'].forEach(method => {
  25. console[`_${method}`] = console[method];
  26. console[method] = (function(origMethod) {
  27. return function() {
  28. const args = Array.from(arguments);
  29. const suffix = `@ ${
  30. this.lineNumber
  31. ? `${this.fileName}:${this.lineNumber}:1`
  32. : extractLineNumberFromStack(new Error().stack)
  33. }`;
  34. origMethod.apply(console, args.concat([suffix]));
  35. try {
  36. ipcRenderer.send(
  37. 'console_log',
  38. windowId,
  39. method === 'log' ? 'info' : method,
  40. JSON.stringify(args)
  41. );
  42. } catch (err) {
  43. console._warn(
  44. 'Unable to stringify arguments to log to backend',
  45. err.stack
  46. );
  47. }
  48. };
  49. })(console[method]);
  50. });
  51. };