-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathnotify_js.go
More file actions
63 lines (52 loc) · 1.33 KB
/
notify_js.go
File metadata and controls
63 lines (52 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//go:build js
package beeep
import (
"encoding/base64"
"fmt"
"syscall/js"
)
// Notify sends desktop notification.
// The icon can be string with a path/url to png file or png []byte data. Stock icon names can also be used where supported.
//
// On the Web it uses the Notification API, in Firefox it just works, in Chrome you must call it from some "user gesture"
// like `onclick`, and you must use TLS certificate, it doesn't work with plain http.
func Notify(title, message string, icon any) (err error) {
defer func() {
e := recover()
if e == nil {
return
}
if e, ok := e.(*js.Error); ok {
err = e
} else {
panic(e)
}
}()
var img string
switch i := icon.(type) {
case string:
img = i
case []byte:
img = fmt.Sprintf("data:image/png;base64, %s", base64.StdEncoding.EncodeToString(i))
default:
return fmt.Errorf("unsupported argument: %T", icon)
}
n := js.Global().Get("Notification")
opts := js.Global().Get("Object").Invoke()
opts.Set("body", message)
opts.Set("icon", img)
if n.Get("permission").String() == "granted" {
n.New(js.ValueOf(title), opts)
} else {
var f js.Func
f = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
if args[0].String() == "granted" {
n.New(js.ValueOf(title), opts)
}
f.Release()
return nil
})
n.Call("requestPermission", f)
}
return
}