How to expose python functions in javascript with cefpython with an external HTML file

218 Views Asked by At

I’m trying to write an HTML GUI for a project with cefpython. I’ve been able to create a working GUI in HTML, but I’d like to be able to expose python functions in javascript. There’s a tutorial on how to do this in the cefpython GitHub repo, but it involves writing your HTML in a string in the python program and converting it into a data URI. Is there a way to interface python and javascript while keeping your HTML in a separate file? Right now, I’ve passed cefpython the address of my HTML file as the URL to open, but I don’t necessarily need to use that method. I just want to have HTML in an external file and call a python function from javascript run on that page (so that I can call a python function by pressing a button on the page.)

Edit: My question is: how do I call a python function from javascript contained in an external HTML file, using the cefpython library?

from cefpython3 import cefpython as cef
import sys, os

sys.excepthook = cef.ExceptHook
cef.Initialize()
cef.CreateBrowserSync(url="file:///./main.html")
cef.MessageLoop()
cef.Shutdown()
1

There are 1 best solutions below

0
On

Probably too late for an answer, but yeah..

Define a function to bind the objects/functions/properties in python you want to be accessed in javascript.

from cefpython3 import cefpython as cef
import sys, os

sys.excepthook = cef.ExceptHook
cef.Initialize()
browser = cef.CreateBrowserSync(url="file:///./main.html")
set_javascript_bindings(browser)
cef.MessageLoop()
cef.Shutdown()

def set_javascript_bindings(browser):
    bindings = cef.JavascriptBindings(
        bindToFrames=False, bindToPopups=False)
    bindings.SetObject("object_name_in_js", your-object-in-python)
    bindings.SetProperty("property_name_in_js", your-property-in-python)
    bindings.SetFunction("function_name_in_js", your-function-in-python)
    browser.SetJavascriptBindings(bindings)

Here, "object_name_in_js" and the like will be how you call your objects and functions in javascript. your-object-in-python and the like are their names in the python file. Then, in your js file, (or in the script tag of your html file), refer them directly.

function_name_in_js()
property_name_in_js = ...

and so on. Hope this helps someone!