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

封装注入脚本

master
yutent 2023-07-25 12:29:31 +08:00
parent ba5edd93a4
commit af29a63061
3 changed files with 52 additions and 17 deletions

19
app.js
View File

@ -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)
})
}

View File

@ -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
})

18
main.py
View File

@ -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):