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:
|
2023-09-06 12:21:56 +08:00
|
|
|
def __init__(self, webview, env = {}):
|
2023-08-31 16:57:55 +08:00
|
|
|
|
|
|
|
self.manager = webview.get_user_content_manager()
|
|
|
|
|
2023-09-08 18:55:49 +08:00
|
|
|
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
|
2023-09-12 14:12:29 +08:00
|
|
|
lang, charset = env['LANG'].split('.')
|
|
|
|
|
2023-09-08 18:55:49 +08:00
|
|
|
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)
|
2023-09-12 14:12:29 +08:00
|
|
|
code = code.replace("{{lang}}", lang)
|
2023-09-08 18:55:49 +08:00
|
|
|
|
|
|
|
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)
|