javascriptpythonchromium-embeddedcefpython

CEF Python ExecuteJavascript will not set value of a input element


When I try browser.ExecuteJavascript("alert('ExecuteJavaScript works!');") it works fine (pops up a alert when the browser is created). When I try browser.ExecuteJavascript("document.getElementsByName('q')[0].value = 24;") nothing happens. So I know that ExecuteJavascript is working but how come when I try to set a value of an input element, the input element doesn't change? The code I am trying is below if anyone has an idea as for why that particular Javascript will not execute I would be very grateful.

from cefpython3 import cefpython as cef
import platform
import sys

def main():
    sys.excepthook = cef.ExceptHook
    cef.Initialize()
    browser = cef.CreateBrowserSync(url="https://www.google.com", window_title="Hello World!")
    browser.ExecuteJavascript("document.getElementsByName('q')[0].value = 24")
    cef.MessageLoop()
    cef.Shutdown()

if __name__ == '__main__':
    main()

Solution

  • DOM is not yet ready after the browser was just created. Open Developer Tools window using mouse context menu and you will see the error. You should use LoadHandler to detect when window finishes loading of web page or when DOM is ready. Options:

    1. Implement LoadHandler.OnLoadingStateChange:
    
        main():
            browser.SetClientHandler(LoadHandler())
    
        class LoadHandler(object):
            def OnLoadingStateChange(self, browser, is_loading, **_):
                if not is_loading:
                    browser.ExecuteJavascript("document.getElementsByName('q')[0].value = 24")
    
    1. Implement LoadHandler.OnLoadStart and inject js code that adds an event listener DOMContentLoaded that will execute the actual code.

    See Tutorial > Client handlers: https://github.com/cztomczak/cefpython/blob/master/docs/Tutorial.md#client-handlers

    See also API reference for LoadHandler.