|
| 1 | +""" |
| 2 | +Communicate between Python and Javascript asynchronously using |
| 3 | +inter-process messaging with the use of Javascript Bindings. |
| 4 | +""" |
| 5 | + |
| 6 | +from cefpython3 import cefpython as cef |
| 7 | + |
| 8 | +g_htmlcode = """ |
| 9 | +<!doctype html> |
| 10 | +<html> |
| 11 | +<head> |
| 12 | + <style> |
| 13 | + body, html { |
| 14 | + font-family: Arial; |
| 15 | + font-size: 11pt; |
| 16 | + } |
| 17 | + </style> |
| 18 | + <script> |
| 19 | + function print(msg) { |
| 20 | + console.log(msg+" [JS]"); |
| 21 | + document.getElementById("console").innerHTML += msg+"<br>"; |
| 22 | + } |
| 23 | + function js_function(value) { |
| 24 | + print("Value sent from Python: <b>"+value+"</b>"); |
| 25 | + py_function("I am a Javascript string #1", js_callback); |
| 26 | + } |
| 27 | + function js_callback(value, py_callback) { |
| 28 | + print("Value sent from Python: <b>"+value+"</b>"); |
| 29 | + py_callback("I am a Javascript string #2"); |
| 30 | + } |
| 31 | + </script> |
| 32 | +</head> |
| 33 | +<body> |
| 34 | + <h1>Javascript Bindings</h1> |
| 35 | + <div id=console></div> |
| 36 | +</body> |
| 37 | +</html> |
| 38 | +""" |
| 39 | + |
| 40 | + |
| 41 | +def main(): |
| 42 | + cef.Initialize() |
| 43 | + browser = cef.CreateBrowserSync(url=cef.GetDataUrl(g_htmlcode), |
| 44 | + window_title="OnBeforeClose") |
| 45 | + browser.SetClientHandler(LifespanHandler()) |
| 46 | + bindings = cef.JavascriptBindings() |
| 47 | + bindings.SetFunction("py_function", py_function) |
| 48 | + bindings.SetFunction("py_callback", py_callback) |
| 49 | + browser.SetJavascriptBindings(bindings) |
| 50 | + cef.MessageLoop() |
| 51 | + del browser |
| 52 | + cef.Shutdown() |
| 53 | + |
| 54 | + |
| 55 | +def py_function(value, js_callback): |
| 56 | + print("Value sent from Javascript: "+value) |
| 57 | + js_callback.Call("I am a Python string #2", py_callback) |
| 58 | + |
| 59 | + |
| 60 | +def py_callback(value): |
| 61 | + print("Value sent from Javascript: "+value) |
| 62 | + |
| 63 | + |
| 64 | +class LifespanHandler(object): |
| 65 | + def OnLoadEnd(self, browser, **_): |
| 66 | + browser.ExecuteFunction("js_function", "I am a Python string #1") |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == '__main__': |
| 70 | + main() |
0 commit comments