主机页面与 IFrame 中运行的 JupyterLite 实例之间的通信#
当 JupyterLite 实例通过 IFrame 嵌入到网站中时,可能需要建立主机页面和该实例之间的通信通道。
使用 jupyter-iframe-commands
扩展#
jupyter-iframe-commands 扩展是一个 JupyterLab 扩展,它提供了一个 API,用于在 JupyterLite 嵌入到 iframe 中时,从主机页面执行 JupyterLab 命令。
安装#
在您的环境中安装扩展
pip install jupyter-iframe-commands
然后重建您的 JupyterLite 站点
jupyter lite build
用法#
该扩展由两个包组成
jupyter-iframe-commands
:在 iframe 中运行的 JupyterLab 扩展jupyter-iframe-commands-host
:用于与 JupyterLite 实例交互的主机页面的 JavaScript 包
要在您的主机页面中使用此扩展
<html>
<head>
<title>JupyterLite in an iframe</title>
<script type="module">
import { createBridge } from 'jupyter-iframe-commands-host';
// Create a bridge to the JupyterLite instance
const commandBridge = createBridge({ iframeId: 'jupyter-iframe' });
// Example: Toggle the left sidebar
async function toggleLeftSidebar() {
await commandBridge.execute('application:toggle-left-area');
}
// Example: Change the theme
async function setDarkTheme() {
await commandBridge.execute('apputils:change-theme', {
theme: 'JupyterLab Dark',
});
}
// List all available JupyterLab commands
async function listCommands() {
const commands = await commandBridge.listCommands();
console.log(commands);
}
// Make functions available globally
window.toggleLeftSidebar = toggleLeftSidebar;
window.setDarkTheme = setDarkTheme;
window.listCommands = listCommands;
</script>
</head>
<body>
<h2>JupyterLite with command bridge</h2>
<div>
<button onclick="toggleLeftSidebar()">Toggle Left Sidebar</button>
<button onclick="setDarkTheme()">Set Dark Theme</button>
<button onclick="listCommands()">List Commands (check console)</button>
</div>
<iframe
id="jupyter-iframe"
src="path/to/jupyterlite/"
width="100%"
height="600px"
sandbox="allow-scripts allow-same-origin"
></iframe>
</body>
</html>
jupyter-iframe-commands
扩展提供对所有 JupyterLab 命令的访问,因此您可以控制 JupyterLite 实例的各个方面,例如
切换 UI 元素(侧边栏、面板等)
创建新的笔记本或文件
更改主题
有关更多信息,请参阅 jupyter-iframe-commands 存储库。
暴露额外功能#
如果您需要 jupyter-iframe-commands
扩展之外的额外功能,您可以开发自己的自定义 JupyterLab 扩展。自定义扩展可以实现新命令,以向主机页面暴露更多功能。
有关开发 JupyterLab 扩展的信息,请参阅 JupyterLab 扩展开发人员指南。