diff --git a/app.js b/app.js index 20cd91e..2bde6c8 100644 --- a/app.js +++ b/app.js @@ -7,25 +7,20 @@ import 'es.shim' import { $, bind } from 'wkit' -async function test1() { +function test1() { try { - var result = window.webkit.messageHandlers.app.postMessage({ - value: 'Test 1' + window.webkit.messageHandlers.app.postMessage({ + data: { foo: 'Test 1' } }) - $('#output').innerHTML = 'output: ' + result + $('#output').innerHTML = '这是没有回调的 ' } catch (err) { alert(err) } } -async function test2() { - let key = 'cb_' + Math.random().toString().slice(2) - native.$on(key, function (v) { - $('#output').innerHTML = v - }) - await window.webkit.messageHandlers.app.postMessage({ - value: new Date(), - key +function test2() { + native.handler('blabla', { foo: 'bar' }).then(r => { + $('#output').innerHTML = JSON.stringify(r) }) } diff --git a/inject.js b/inject.js index 1b09817..0840957 100644 --- a/inject.js +++ b/inject.js @@ -4,6 +4,31 @@ * @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) @@ -52,3 +77,10 @@ class EventEmitter { } window.native = new EventEmitter() + +Object.assign(native, { + fs: { + read(filepath) {} + }, + handler +}) diff --git a/main.py b/main.py index a0e9701..dd51dda 100755 --- a/main.py +++ b/main.py @@ -79,12 +79,20 @@ class WebKitWindow(Gtk.Window): data = message.get_js_value() data = json.loads(data.to_json(0)) print('这是py收到的值: ',data) - key = data.get('key') + event = data.get('event') + callback = data.get('callback') + res = {"foo": 123, "bar": (11,22,33)} - if key : - scripts = 'native.$emit("' + key + '", "这是py返回的值 ' + data.get('value') + '")' - self.webview.evaluate_javascript(scripts, -1) - + match event: + case 'fs': + pass + + case _: + if callback : + scripts = 'native.$emit("' + callback + '",' + json.dumps(res) + ')' + print(scripts) + self.webview.evaluate_javascript(scripts, -1) + def on_decide_policy(self, webview, decision, decision_type):