tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

chrome_handler.py (2155B)


      1 import contextlib
      2 
      3 from support.context import using_context
      4 
      5 
      6 def register_chrome_handler(session, manifest_path, entries):
      7    with using_context(session, "chrome"):
      8        return session.execute_script(
      9            """
     10                const { FileUtils } = ChromeUtils.importESModule(
     11                    "resource://gre/modules/FileUtils.sys.mjs"
     12                  );
     13 
     14                const [manifestPath, entries] = arguments;
     15 
     16                const manifest = new FileUtils.File(manifestPath);
     17                const rootURI = Services.io.newFileURI(manifest.parent);
     18                const manifestURI = Services.io.newURI(manifest.leafName, null, rootURI);
     19 
     20                const handle = Cc["@mozilla.org/addons/addon-manager-startup;1"]
     21                    .getService(Ci.amIAddonManagerStartup)
     22                    .registerChrome(manifestURI, entries);
     23                const id = Services.uuid.generateUUID().toString().slice(1, -1);
     24 
     25                if (globalThis.chromeProtocolHandles) {
     26                    globalThis.chromeProtocolHandles.set(id, handle);
     27                }
     28 
     29                return id;
     30 
     31            """,
     32            args=[manifest_path, entries],
     33        )
     34 
     35 
     36 def unregister_chrome_handler(session, id):
     37    with using_context(session, "chrome"):
     38        return session.execute_script(
     39            """
     40                const [id] = arguments;
     41 
     42                if (globalThis.chromeProtocolHandles) {
     43                    if (!globalThis.chromeProtocolHandles.has(id)) {
     44                        throw new Error(
     45                            `Id ${id} is not a known chrome protocol handler`
     46                        );
     47                    }
     48 
     49                    const handle = globalThis.chromeProtocolHandles.get(id);
     50                    globalThis.chromeProtocolHandles.delete(id);
     51                    handle.destruct();
     52                }
     53            """,
     54            args=[id],
     55        )
     56 
     57 
     58 @contextlib.contextmanager
     59 def using_chrome_handler(session, manifest_path, entries):
     60    id = register_chrome_handler(session, manifest_path, entries)
     61 
     62    try:
     63        yield
     64    finally:
     65        unregister_chrome_handler(session, id)