energy/example/execute-javascript/execute-javascript.go

69 lines
1.9 KiB
Go
Raw Normal View History

2022-11-23 15:40:47 +08:00
package main
import (
"embed"
"fmt"
2023-05-31 18:00:34 +08:00
"github.com/energye/energy/v2/cef"
2023-06-07 16:36:18 +08:00
"github.com/energye/energy/v2/common"
2023-05-31 18:00:34 +08:00
"github.com/energye/energy/v2/pkgs/assetserve"
2023-05-31 17:41:14 +08:00
"github.com/energye/golcl/lcl"
2022-11-23 15:40:47 +08:00
"time"
)
//go:embed resources
var resources embed.FS
func main() {
//全局初始化 每个应用都必须调用的
cef.GlobalInit(nil, &resources)
2022-11-23 15:40:47 +08:00
//创建应用
2023-02-28 18:41:12 +08:00
cefApp := cef.NewApplication()
2022-11-23 15:40:47 +08:00
//指定一个URL地址或本地html文件目录
cef.BrowserWindow.Config.Url = "http://localhost:22022/execute-javascript.html"
2022-11-23 15:40:47 +08:00
cef.BrowserWindow.Config.Title = "Energy - execute-javascript"
2023-06-07 16:36:18 +08:00
if common.IsLinux() {
cef.BrowserWindow.Config.IconFS = "resources/icon.png"
} else {
cef.BrowserWindow.Config.IconFS = "resources/icon.ico"
}
2022-11-23 15:40:47 +08:00
//内置http服务链接安全配置
cef.SetBrowserProcessStartAfterCallback(func(b bool) {
fmt.Println("主进程启动 创建一个内置http服务")
//通过内置http服务加载资源
server := assetserve.NewAssetsHttpServer()
server.PORT = 22022
server.AssetsFSName = "resources" //必须设置目录名
server.Assets = &resources
go server.StartHttpServer()
//定时执行web js
go timeTask()
})
2023-05-31 17:41:14 +08:00
cef.BrowserWindow.SetBrowserInit(func(event *cef.BrowserEvent, window cef.IBrowserWindow) {
window.Chromium().SetOnLoadEnd(func(sender lcl.IObject, browser *cef.ICefBrowser, frame *cef.ICefFrame, httpStatusCode int32) {
var jsCode = `
(function(){
console.log("执行");
})();
`
window.Chromium().ExecuteJavaScript(jsCode, "", 0)
})
})
2022-11-23 15:40:47 +08:00
//运行应用
cef.Run(cefApp)
}
//定时执行web js
func timeTask() {
var param0 = 0
for {
//每1秒钟执行一次
time.Sleep(time.Second)
info := cef.BrowserWindow.MainWindow()
param0++
//调用js中定义的函数GoExecuteJSFunc,并传递参数,但没有返回值
var jsFunc = fmt.Sprintf("GoExecuteJSFunc(%d, '%d')", param0, time.Now().Second())
fmt.Println("GoExecuteJSFunc:", jsFunc)
info.Chromium().ExecuteJavaScript(jsFunc, "", 0)
}
}