python3-webengine-gtk3/usr/lib/python3/dist-packages/webengine/gtk3/_inject.py

38 lines
1.1 KiB
Python
Raw Normal View History

2023-08-31 16:57:55 +08:00
#!/usr/bin/env python3
# @author yutent<yutent.io@gmail.com>
# @date 2023/08/08 15:00:27
2023-09-04 18:29:12 +08:00
import os, gi, json
2023-08-31 16:57:55 +08:00
gi.require_version("WebKit2", "4.1")
from gi.repository import WebKit2
class Inject:
def __init__(self, webview, env = {}):
2023-08-31 16:57:55 +08:00
self.manager = webview.get_user_content_manager()
code = open(self.abspath('./inject.js'), 'r').read()
2023-08-31 16:57:55 +08:00
frame = WebKit2.UserContentInjectedFrames.ALL_FRAMES
time = WebKit2.UserScriptInjectionTime.END
code = code.replace("'{{env}}'", json.dumps(env))
code = code.replace("{{uuid}}", webview.uuid)
code = code.replace("{{app_name}}", webview.app_name)
code = code.replace("{{app_version}}", webview.app_version)
script = WebKit2.UserScript(code, frame, time, None, None)
2023-08-31 16:57:55 +08:00
self.manager.add_script(script)
def connect(self, callback):
self.manager.connect('script-message-received::app', callback)
self.manager.register_script_message_handler('app')
def abspath(self, filepath):
root = os.path.dirname(os.path.realpath(__file__))
return os.path.join(root, filepath)