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-21 19:13:51 +08:00
commit aba79c47b4
6 changed files with 236 additions and 0 deletions

4
.httpserver Normal file
View File

@ -0,0 +1,4 @@
{
"enabled": true,
"port": 10086
}

34
app.js Normal file
View File

@ -0,0 +1,34 @@
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/07/20 14:19:13
*/
import 'es.shim'
import { $, bind } from 'wkit'
async function test1() {
try {
var result = await window.webkit.messageHandlers.app.postMessage({
value: 'Test 1'
})
$('#output').innerHTML = 'output: ' + result
} catch (err) {
alert(err)
}
}
async function test2() {
let key = 'cb_' + Math.random().toString().slice(2)
window.$on(key, function (v) {
$('#output').innerHTML = v
})
window.webkit.messageHandlers.app.postMessage({
value: new Date(),
key
})
$('#output').innerHTML = result
}
bind($('.btn1'), 'click', test1)
bind($('.btn2'), 'click', test2)

32
index.html Normal file
View File

@ -0,0 +1,32 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
<title></title>
<script type="importmap">
{
"imports":{
"es.shim":"//jscdn.ink/es.shim/latest/index.js",
"wkit":"//jscdn.ink/wkit/latest/index.js",
"vue":"//jscdn.ink/vue/3.2.47/vue.esm-browser.prod.js",
"vue-router":"//jscdn.ink/@bytedo/vue-router/4.1.6/vue-router.js","fetch":"//jscdn.ink/@bytedo/fetch/latest/next.js",
"crypto":"//jscdn.ink/crypto.web.js/latest/index.js"
}
}
</script>
</head>
<body>
<button class="btn1">Test 1</button>
<button class="btn2">Test 2</button>
<a target="_blank" href="about:blank">打开控制台</a>
<div id="output">loading...</div>
<script type="module" src="/app.js"></script>
</body>
</html>

52
inject.js Normal file
View File

@ -0,0 +1,52 @@
/**
* {注入的js}
* @author yutent<yutent.io@gmail.com>
* @date 2023/07/21 17:38:11
*/
Object.assign(window, {
//
__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)
}
})

92
main.py Executable file
View File

@ -0,0 +1,92 @@
#!/usr/bin/python3
import gi, json, os
gi.require_version("Gtk", "3.0")
gi.require_version("WebKit2", "4.1")
# gi.require_version("JavaScriptCore", "4.1")
from gi.repository import Gtk, WebKit2, JavaScriptCore
class MyScriptMessageHandler(WebKit2.ScriptMessageReply):
def __init__(self):
super().__init__()
class WebKitWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="WebKit Example")
self.set_default_size(800, 600)
settings = WebKit2.Settings()
settings.set_enable_page_cache(True)
settings.set_enable_offline_web_application_cache(True)
settings.set_property('javascript-can-access-clipboard', True)
settings.set_property('javascript-can-open-windows-automatically', True)
settings.set_property("user-agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) weapp/1.0.0 Version/16.4 Safari/605.1.15")
manager = WebKit2.UserContentManager()
script = open(self.file_path('./inject.js'), 'r').read()
frame = WebKit2.UserContentInjectedFrames.ALL_FRAMES
time = WebKit2.UserScriptInjectionTime.END
script = WebKit2.UserScript(script, frame, time, None, None)
manager.add_script(script)
manager.connect('script-message-received::app', self.on_script_message)
manager.register_script_message_handler('app')
self.webview = WebKit2.WebView.new_with_user_content_manager(manager)
self.webview.set_settings(settings)
self.webview.connect("decide-policy", self.on_decide_policy)
self.webview.load_uri("http://127.0.0.1:10086/index.html")
# self.webview.load_uri("https://benchmark.wkit.fun")
self.add(self.webview)
def file_path(self, filepath):
root = os.path.dirname(os.path.realpath(__file__))
return os.path.join(root, filepath)
def on_script_message(self, webview, message):
data = message.get_js_value()
data = json.loads(data.to_json(0))
print('这是py收到的值: ',data)
key = data.get('key')
if key :
scripts = '$emit("' + key + '", "这是py返回的值 ' + data.get('value') + '")'
self.webview.evaluate_javascript(scripts, -1)
def on_decide_policy(self, webview, decision, decision_type):
if decision_type == WebKit2.PolicyDecisionType.NAVIGATION_ACTION:
navigation_action = decision.get_navigation_action()
request = navigation_action.get_request()
uri = request.get_uri()
if uri == "about:blank":
# Open the developer tools window
inspector = webview.get_inspector()
inspector.show()
else:
decision.use()
win = WebKitWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

22
setup.py Executable file
View File

@ -0,0 +1,22 @@
#!/usr/bin/python3
from setuptools import setup
setup(
name='myapp',
version='0.1',
description='My GTK3 + WebKit2 application',
author='Your Name',
author_email='your@email.com',
url='https://github.com/yourusername/myapp',
py_modules=['main'],
install_requires=[
'gi',
'webkit2gtk',
],
entry_points={
'gui_scripts': [
'myapp=main:WebKitWindow'
]
},
)