Search code examples
pythonselenium-webdriverundetected-chromedriverchrome-devtools-protocolseleniumbase

SeleniumBase CDP mode execute_script and evaluate with javascript gives error "SyntaxError: Illegal return statement"


I am using SeleniumBase in CDP Mode.

I am having a hard time figuring out if this a python issue or SeleniumBase issue.

The below simple example shows my problem:

from seleniumbase import SB

with SB(uc=True, locale_code="en", headless=True) as sb:

    link = "https://news.ycombinator.com"
    
    print(f"\nOpening {link}")

    sb.wait_for_ready_state_complete(timeout=120)

    sb.activate_cdp_mode(link)

    script = f"""
function getSomeValue() {{
    return '42';
}}

return getSomeValue();
"""
    
    # data = sb.execute_script(script)
    data = sb.cdp.evaluate(script)

    print(data)

    print("Finished!")

This throws error:

seleniumbase.undetected.cdp_driver.connection.ProtocolException: 
exceptionId: 1
text: Uncaught
lineNumber: 5
columnNumber: 4
scriptId: 6
exception: 
        type: object
        subtype: error
        className: SyntaxError
        description: SyntaxError: Illegal return statement
        objectId: 3089353218542582072.1.2

Notice above that I have tried both sb.execute_script(script) and sb.cdp.evaluate(script) and both give the same issue.

How can I execute such scripts?


Solution

  • In CDP Mode, don't include the final return when evaluating JS.

    Your script part should look like this:

    script = f"""
    function getSomeValue() {{
        return '42';
    }}
    
    getSomeValue();
    """
    
    data = sb.cdp.evaluate(script)
    

    (Instead of using "return getSomeValue();", which breaks evaluate(expression).)