#!/usr/bin/env python3 # @author yutent # @date 2023/08/08 15:00:27 import os, gi, json gi.require_version("WebKit2", "4.1") from gi.repository import WebKit2 class Inject: def __init__(self, webview, env = {}): self.manager = webview.get_user_content_manager() code = open(self.abspath('./inject.js'), 'r').read() frame = WebKit2.UserContentInjectedFrames.ALL_FRAMES time = WebKit2.UserScriptInjectionTime.START 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) 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)