UNPKG

2.04 kBJavaScriptView Raw
1// Script injected by @ionic/angular-toolkit to send console logs back
2// to a websocket server so they can be printed to the terminal
3window.Ionic = window.Ionic || {}; window.Ionic.ConsoleLogServer = {
4 start: function(config) {
5 var self = this;
6
7 this.socket = new WebSocket('ws://' + window.location.hostname + ':' + String(config.wsPort));
8 this.msgQueue = [];
9
10 this.socket.onopen = function() {
11 self.socketReady = true;
12
13 self.socket.onclose = function() {
14 self.socketReady = false;
15 console.warn('Console log server closed');
16 };
17 };
18
19 this.patchConsole();
20 },
21
22 queueMessageSend: function(msg) {
23 this.msgQueue.push(msg);
24 this.drainMessageQueue();
25 },
26
27 drainMessageQueue: function() {
28 var msg;
29 while (msg = this.msgQueue.shift()) {
30 if (this.socketReady) {
31 try {
32 this.socket.send(JSON.stringify(msg));
33 } catch(e) {
34 if (!(e instanceof TypeError)) {
35 console.error('ws error: ' + e);
36 }
37 }
38 }
39 }
40 },
41
42 patchConsole: function() {
43 var self = this;
44
45 function _patchConsole(consoleType) {
46 console[consoleType] = (function() {
47 var orgConsole = console[consoleType];
48 return function() {
49 orgConsole.apply(console, arguments);
50 var msg = {
51 category: 'console',
52 type: consoleType,
53 data: []
54 };
55 for (var i = 0; i < arguments.length; i++) {
56 msg.data.push(arguments[i]);
57 }
58 if (msg.data.length) {
59 self.queueMessageSend(msg);
60 }
61 };
62 })();
63 }
64
65 // https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-console/#supported-methods
66 var consoleFns = ['log', 'error', 'exception', 'warn', 'info', 'debug', 'assert', 'dir', 'dirxml', 'time', 'timeEnd', 'table'];
67 for (var i in consoleFns) {
68 _patchConsole(consoleFns[i]);
69 }
70 },
71};
72
73Ionic.ConsoleLogServer.start(Ionic.ConsoleLogServerConfig || {});