Search code examples
seleniumselenium-chromedrivermutation-observers

to set MutationObserver, How to inject javascript before page-loading using Selenium


I'm trying to set MutationObserver for observing page mutation while loading.

In order to do that, MutationObserver should be configured before page loading.

With selenium-chromedriver, couldn't find the way to inject JS for such purpose.

I know chrome extension can do that but extensions won't work on headless mode.

That's the problem.


Solution

  • We can now use execute_cdp_cmd(cmd, cmd_args) to execute Chrome Devtools Protocol command in Selenium

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    
    driver.execute_cdp_cmd(
        "Page.addScriptToEvaluateOnNewDocument",
        {
            "source": """// Your JavaScript here"""
        }
    )
    
    driver.get("https://stackoverflow.com")
    driver.quit()
    

    The argument for "source" is just a string. So you can actually write your script in a .js file (for syntax highlighting) and read it using Python