You can hijack JavaScript functions in the following manner:
(function(){
var oldLog = console.log;
console.log = function (message) {
// DO MESSAGE HERE.
oldLog.apply(console, arguments);
};
})();
- Line 1 wraps your function in a closure so no other functions have direct access to
oldLog
(for maintainability reasons).
- Line 2 captures the original method.
- Line 3 creates a new function.
- Line 4 is where you send
message
to your server.
- Line 5 is invokes the original method as it would have been handled originally.
apply
is used so we can invoke it on console
using the original arguments. Simply calling oldLog(message)
would fail because log
depends on its association with console
.
Update Per zzzzBov's comment below, in IE9 console.log
isn't actually a function so oldLog.apply
would fail. See console.log.apply not working in IE9 for more details.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…