87 lines
1.5 KiB
JavaScript
87 lines
1.5 KiB
JavaScript
/**
|
|
* {注入的js}
|
|
* @author yutent<yutent.io@gmail.com>
|
|
* @date 2023/07/21 17:38:11
|
|
*/
|
|
|
|
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
|
|
}
|
|
|
|
class EventEmitter {
|
|
//
|
|
__events__ = Object.create(null)
|
|
|
|
$on(name, fn) {
|
|
if (this.__events__[name]) {
|
|
this.__events__[name].push(fn)
|
|
} else {
|
|
this.__events__[name] = [fn]
|
|
}
|
|
}
|
|
|
|
$once(name, fn) {
|
|
fn.__once__ = true
|
|
this.$on(name, fn)
|
|
}
|
|
|
|
$off(name, fn) {
|
|
if (this.__events__[name]) {
|
|
if (fn) {
|
|
this.__events__[name] = this.__events__[name].filter(it => it !== fn)
|
|
} else {
|
|
this.__events__[name] = []
|
|
}
|
|
}
|
|
}
|
|
|
|
$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)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
$destroy() {
|
|
this.__events__ = Object.create(null)
|
|
}
|
|
}
|
|
|
|
window.native = new EventEmitter()
|
|
|
|
Object.assign(native, {
|
|
fs: {
|
|
read(filepath) {}
|
|
},
|
|
handler
|
|
})
|
Python
60.1%
JavaScript
37.6%
HTML
2.3%