我已经实现了一个 JS 模块,我从多个 Node.js 脚本中使用它。
我希望也能够从浏览器中使用此模块,并且我希望所有消息都显示在 HTML 警报框中而不是终端中。
理想情况下,我希望在不更改 JS 模块的情况下实现此目的(例如,通过将所有出现的 console.log
替换为 alert
,或者通过传递日志记录当我初始化模块时函数)。
所以我想我可以在从我拥有的客户端代码中使用此模块之前简单地设置 console.log =alert
。
重要的是,我实际上是用 Electron 来做这件事的。 (使用JavaScript的跨平台桌面应用程序),但我也在浏览器上测试过,结果是一样的。
使用 console.log =alert
,我成功地将 console.log
从 function log() {[native code]}
更改为函数alert() {[ native 代码]}
。
但是,当我尝试调用 console.log("test")
时,我收到异常 TypeError: Illegal inspiration
。
这是一个简单的客户端代码,可以重现此问题:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
try{
alert(`before:\n- alert = ${alert}\n- console.log = ${console.log}`);
console.log = alert;
alert(`after:\n- alert = ${alert}\n- console.log = ${console.log}`);
console.log("test");
}
catch (error) {
alert(error);
}
</script>
</body>
</html>
为什么我会遇到这个问题,以及如何解决它(最好不更改我的 JS 模块)?
是否有可能alert
最终调用console.log
,从而产生某种无限递归?
最佳答案
this
的值(value)很重要。
alert
期望 this
为 window
而不是 console
。
因此:
console.log = window.alert.bind(window);
关于javascript - 重定向到 'console.log' 后无法使用 'alert',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55558121/