You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter Lab中JavaScript无法运行问题求助

Jupyter Lab中ipwidgets无法运行JavaScript的排查方案

在Jupyter Lab环境使用ipwidgets搭建仪表盘时,JavaScript完全无法执行,即使在全新沙箱环境中问题依旧,但相同代码在Google Colab可正常运行。测试代码如下:

from IPython.display import Javascript, display
import ipywidgets as widgets

# Define a function to display a JavaScript alert
def show_alert():
    display(Javascript('alert("Hello from JavaScript!")'))

# Create a button widget
button = widgets.Button(description="Click me!")

# Set the button's action
button.on_click(lambda b: show_alert())

# Display the button
display(button)

以下是针对性的排查和解决步骤:

  • 检查Jupyter Lab扩展状态
    运行jupyter labextension list确认@jupyter-widgets/jupyterlab-manager已安装启用。若缺失,执行对应安装命令:

    # 基础安装
    pip install ipwidgets
    # 启用经典 notebook 扩展(若同时使用)
    jupyter nbextension enable --py widgetsnbextension
    # Jupyter Lab 2.x及以下版本安装扩展
    jupyter labextension install @jupyter-widgets/jupyterlab-manager
    # Jupyter Lab 3.0+版本直接通过pip安装
    pip install jupyterlab-widgets
    

    完成后重启Jupyter Lab。

  • 排查浏览器控制台报错
    打开浏览器开发者工具(F12)切换到Console标签,查看是否存在JS资源加载失败、内容安全策略(CSP)拦截等报错。若存在CSP限制,可修改Jupyter配置文件jupyter_notebook_config.py:

    c.NotebookApp.tornado_settings = {
        'headers': {
            'Content-Security-Policy': "default-src 'self' 'unsafe-inline' 'unsafe-eval'; script-src 'self' 'unsafe-inline' 'unsafe-eval';"
        }
    }
    

    保存后重启Jupyter Lab。

  • 验证基础JavaScript执行能力
    先运行简化代码排查是否为ipwidgets特定问题:

    from IPython.display import Javascript, display
    display(Javascript('console.log("Test JS execution")'))
    

    查看浏览器控制台是否输出Test JS execution,以此确认基础JS通信是否正常。

  • 确认版本兼容性
    检查ipwidgets、Jupyter Lab、IPython的版本是否匹配,执行命令查看版本:

    pip list | grep -E "ipwidgets|jupyterlab|ipython"
    

    参考官方兼容性说明调整版本,例如ipwidgets 8.x需搭配Jupyter Lab 3.x及以上版本。

内容的提问来源于stack exchange,提问作者Amaan Iqbal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 20:04:56