#!/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() script_data = open(self.abspath('./inject.js'), 'r').read() frame = WebKit2.UserContentInjectedFrames.ALL_FRAMES time = WebKit2.UserScriptInjectionTime.END script_data = script_data.replace("'{{env}}'", json.dumps(env)) script = WebKit2.UserScript(script_data, 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)