javascript - 重定向到 'console.log' 后无法使用 'alert'

标签 javascript node.js alert console.log

我已经实现了一个 JS 模块,我从多个 Node.js 脚本中使用它。

我希望也能够从浏览器中使用此模块,并且我希望所有消息都显示在 HTML 警报框中而不是终端中。

理想情况下,我希望在不更改 JS 模块的情况下实现此目的(例如,通过将所有出现的 console.log 替换为 alert,或者通过传递日志记录当我初始化模块时函数)。

所以我想我可以在从我拥有的客户端代码中使用此模块之前简单地设置 console.log =alert

重要的是,我实际上是用 Electron 来做这件事的。 (使用JavaScript的跨平台桌面应用程序),但我也在浏览器上测试过,结果是一样的。

使用 console.log =alert,我成功地将 console.logfunction 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 期望 thiswindow 而不是 console

因此:

console.log = window.alert.bind(window);

关于javascript - 重定向到 'console.log' 后无法使用 'alert',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55558121/

相关文章:

javascript - 从中删除属性时窗口对象的奇怪行为

javascript - 从 Angular Controller 调用外部库中的函数

javascript - 在 NodeJ 中组合不同的模块

c++ - 向 node.js 添加 OpenCV C++ 附加组件的最基本示例

java-me - 使用 LWUIT 弹出警报

javascript - 使用特定格式对字符串进行排序

javascript - 如何获取父对象的函数(NodeJS模块)

javascript - 为什么我的 readFileSync 函数没有执行?

javascript - 多次异步调用后回调?

javascript - 为什么 "Prevent this page from creating additional dialogs"出现在警告框中?