-1
問題:在開發Ionic2應用程序時,我想看到在我的iPhone上生成的console.log消息,但我沒有Mac或我確實有一個,但發現Web檢查器功能很爛。如何遠程調試console.log
注意這是適用於任何類型的遠程JavaScript中,不僅角/離子。
這是問答&樣式的問題,這意味着我會在下面給出答案,因爲我認爲這是很多人非常有用的。
問題:在開發Ionic2應用程序時,我想看到在我的iPhone上生成的console.log消息,但我沒有Mac或我確實有一個,但發現Web檢查器功能很爛。如何遠程調試console.log
注意這是適用於任何類型的遠程JavaScript中,不僅角/離子。
這是問答&樣式的問題,這意味着我會在下面給出答案,因爲我認爲這是很多人非常有用的。
的解決方案是一個鉤到你的JavaScript將攔截所有的console.log和錯誤,並將它們發送到服務器。
將以下代碼到您的index.html頁面:
<script>
// Function that will call your webserver
logToServer = function(consoleMsg) {
// only do this if on device
if (window.cordova) {
let jsonTxt = customStringify(consoleMsg);
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", 'http://yourserver/console2server.php?msg=' + jsonTxt, true); //async
xmlHttp.send(null);
}
}
// Test if you receive this on the server
logToServer("OPENING IONIC APP");
// intercept console logs
(function() {
var oldLog = console.log;
console.log = function (message) {
// DO MESSAGE HERE.
logToServer(message);
oldLog.apply(console, arguments);
};
})();
// intecept errors
if (window && !window.onerror) {
window.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
logToServer(errorMsg);
logToServer(errorObj);
return false;
}
}
// this is optional, but it avoids 'converting circular structure' errors
customStringify = function (inp) {
return JSON.stringify(inp, function (key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
console.log("circular dep found!!");
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
}
</script>
在服務器端,我使用PHP,但你可以使用任何你想要的:
<?php
//allow CORS request
header('Access-Control-Allow-Origin: *');
if(isset($_GET['msg'])) {
//you can also log to a file or whatever, I just log to standard logs
error_log("[CONSOLE.LOG] ".json_decode($_GET['msg'], true));
}
?>
快樂調試!