This repository has been archived on 2023-09-06. You can view files and clone it, but cannot push or open issues/pull-requests.
yutent
/
py-gtk-notes
Archived
1
0
Fork 0
py-gtk-notes/inject.js

87 lines
1.5 KiB
JavaScript
Raw Normal View History

2023-07-21 19:13:51 +08:00
/**
* {注入的js}
* @author yutent<yutent.io@gmail.com>
* @date 2023/07/21 17:38:11
*/
2023-07-25 12:29:31 +08:00
function defer() {
let obj = {}
obj.promise = new Promise((resolve, reject) => {
obj.resolve = resolve
obj.reject = reject
})
return obj
}
function rand(prefix = 'cb_') {
return prefix + Math.random().toString().slice(2)
}
function handler(event, data = {}, once = true) {
let _ = defer()
let callback = rand()
native[once ? '$once' : '$on'](callback, _.resolve)
window.webkit.messageHandlers.app.postMessage({
event,
data,
callback
})
return _.promise
}
2023-07-24 15:05:01 +08:00
class EventEmitter {
2023-07-21 19:13:51 +08:00
//
2023-07-24 15:05:01 +08:00
__events__ = Object.create(null)
2023-07-21 19:13:51 +08:00
$on(name, fn) {
if (this.__events__[name]) {
this.__events__[name].push(fn)
} else {
this.__events__[name] = [fn]
}
2023-07-24 15:05:01 +08:00
}
2023-07-21 19:13:51 +08:00
$once(name, fn) {
fn.__once__ = true
this.$on(name, fn)
2023-07-24 15:05:01 +08:00
}
2023-07-21 19:13:51 +08:00
$off(name, fn) {
if (this.__events__[name]) {
if (fn) {
this.__events__[name] = this.__events__[name].filter(it => it !== fn)
} else {
this.__events__[name] = []
}
}
2023-07-24 15:05:01 +08:00
}
2023-07-21 19:13:51 +08:00
$emit(name, ...args) {
if (this.__events__[name]) {
for (let fn of this.__events__[name]) {
try {
fn.apply(this, args)
if (fn.__once__) {
this.$off(name, fn)
}
} catch (e) {
console.error(e)
}
}
}
2023-07-24 15:05:01 +08:00
}
2023-07-21 19:13:51 +08:00
$destroy() {
this.__events__ = Object.create(null)
}
2023-07-24 15:05:01 +08:00
}
window.native = new EventEmitter()
2023-07-25 12:29:31 +08:00
Object.assign(native, {
fs: {
read(filepath) {}
},
handler
})