Search code examples
google-chromegoogle-chrome-devtools

Fixed web socket endpoint for Chrome CDP (Chrome DevTools Protocol)


I use Chrome CDP for some tasks automation.

One have to first start the chrome with CDP:

chromium-browser --remote-debugging-port=9222

and it reports something like

DevTools listening on ws://127.0.0.1:9222/devtools/browser/3e3152c6-20fc-4cea-a9d2-60e4e6b8ad70

I have to copy the ws://... URL to my config file manually to be able to proceed with my task. I probably can work around this using python's subprocess.Popen to do this instead and extract the URL but isn't there a way how to make this URL configurable or at least fixed?


Solution

  • Thanks to wOxxOm! It really can be read from http://127.0.0.1:9222/json/version (Documentation)

    As an alternative, I wrote Python script to launch it and get the endpoint as well:

    from subprocess import Popen, PIPE
    
    
    class Browser:
        BANNER = "DevTools listening on "
    
        def __init__(self, path="/usr/bin/chromium-browser",
                port=9222, ignore_tls_errors=False):
    
            cmd = [path, f"--remote-debugging-port={port}"]
            if ignore_tls_errors:
                cmd.append("--ignore-certificate-errors")
    
            self.process = Popen(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True)
    
            output = ""
            for line in self.process.stderr:
                output += line
                if self.BANNER in output:
                    start_pos = output.find(self.BANNER) + len(self.BANNER)
                    end_pos = output.find("\n", start_pos)
                    self.url = output[start_pos:end_pos]
                    break
    
        def close(self):
            self.process.terminate()
    
    
    if __name__ == "__main__":
        try:
            b = Browser()
            print("URL:", b.url)
        finally:
            b.close()