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

如何从WebView的HTML按钮调用Deno应用内的函数?

实现Deno WebView中HTML按钮调用Deno内部函数

当然可以做到!不过你当前的代码里存在一个关键问题:HTML里的test()是在WebView的前端浏览器环境中寻找的,而你定义的test()函数是在Deno的后端环境里,两者不在同一个执行上下文,所以直接点击按钮会报错找不到这个函数。

要实现这个需求,我们需要利用Deno WebView提供的双向通信机制,把Deno端的函数暴露给前端调用。下面是修改后的完整代码:

// Importing the webview library
import { WebView } from "https://deno.land/x/webview/mod.ts";

// Creating an HTML page
let html = `
<html>
<body>
<h1>Hello from deno v${Deno.version.deno}</h1>
<button type="button" onclick="window.deno.test()">RUN TEST FUNCTION</button>
</body>
</html>
`;

function test() {
  console.log('You really can do that!');
  // 可选:调用前端代码给用户反馈
  webview.eval("alert('Test function executed successfully in Deno!')");
}

// Creating and configuring the webview
const webview = new WebView({
  title: "Deno Webview Example",
  url: "data:text/html," + html,
  width: 768,
  height: 1024,
  resizable: true,
  debug: true,
  frameless: false
});

// 把Deno端的test函数绑定到前端全局对象window.deno下
webview.bind("test", test);

// Running the webview
webview.run();

关键说明:

  • 函数绑定:通过webview.bind("test", test)方法,我们把Deno端的test函数注册到前端的window.deno命名空间下,这样前端就能通过window.deno.test()调用它。
  • 执行顺序:绑定操作必须在webview.run()之前完成,不然前端无法找到绑定的函数。
  • 参数传递:如果需要从前端给Deno函数传参也很简单,比如前端写成window.deno.test('Hello from frontend!'),Deno端的函数改成:
    function test(message: string) {
      console.log(message); // 会输出 "Hello from frontend!"
    }
    

运行代码的命令保持不变:

deno run -A --unstable webview.ts

现在点击按钮,你就能在终端看到You really can do that!的输出,同时还会弹出前端提示框,完美实现了前端按钮调用Deno内部函数的需求~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 23:57:40