[思源笔记经验分享] 在 HTML 块中运行系统命令

本贴最后更新于 748 天前,其中的信息可能已经时移世易

原理

原理比较简单, 就是使用 Node.jschild_process 模块创建子进程, 因此只能在桌面版中使用, 同时比较高版本的 PowerShell 支持使用 ; 表示换行, 可以将命令压缩到一行

目前仅适用于 Windows 系统, 不过其他系统也差不多, 改一改换行分隔符与 shell 程序名即可

欢迎使用我的推荐呀: h0sc9rc (*^▽^*)

代码

方案 1: 在 HTML 块中添加 <script>

在思源 v1.9.7+ 才能支持, 详情请参考 支持 HTML 块中使用 JavaScript · Issue #4499 · siyuan-note/siyuan

<script>
function run() {
    let commands = `
ipconfig
pause
systeminfo
`;

    if (window.confirm(commands)) {
        commands = `start powershell -c ${commands.replaceAll('\n', '; ')}pause`;
        require('child_process').exec(commands, null);
    }
}
</script>

<button onclick="run()" type="button" style="width: 128px; height: 32px">系统命令运行测试</button>

方案 2: 在主题 theme.js 中添加函数并在 HTML 块中调用

/* 运行系统命令 */
const child_process = require('child_process');

function runcmd(commands) {
    if (window.confirm(commands)) {
        commands = `start powershell -c ${commands.replaceAll('\n', '; ')}pause`;
        child_process.exec(commands, null);
    }
}
<button onclick="runcmd(`
ipconfig
pause
systeminfo
`)" type="button" style="width: 128px; height: 32px">系统命令运行测试</button>
  • 思源笔记

    思源笔记是一款隐私优先的个人知识管理系统,支持完全离线使用,同时也支持端到端加密同步。

    融合块、大纲和双向链接,重构你的思维。

    18662 引用 • 69557 回帖
2 操作
shuoying 在 2022-04-06 21:40:22 更新了该帖
shuoying 在 2022-04-06 13:05:48 更新了该帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...