Skip to content

Commit 2415a8f

Browse files
committed
Add javascript_bindings.py snippet (cztomczak#403) and others.
Add cef.GetDataUrl(). Update README-examples.md - add Snippets section. Update PyInstaller example.
1 parent 4ba8f58 commit 2415a8f

File tree

13 files changed

+114
-13
lines changed

13 files changed

+114
-13
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,7 @@ Additional information for v31.2 release:
469469
* [GetBrowserByIdentifier](api/cefpython.md#getbrowserbyidentifier)
470470
* [GetBrowserByWindowHandle](api/cefpython.md#getbrowserbywindowhandle)
471471
* [GetCommandLineSwitch](api/cefpython.md#getcommandlineswitch)
472+
* [GetDataUrl](api/cefpython.md#getdataurl)
472473
* [GetGlobalClientCallback](api/cefpython.md#getglobalclientcallback)
473474
* [GetModuleDirectory](api/cefpython.md#getmoduledirectory)
474475
* [GetVersion](api/cefpython.md#getversion)

api/API-index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,7 @@
157157
* [GetBrowserByIdentifier](cefpython.md#getbrowserbyidentifier)
158158
* [GetBrowserByWindowHandle](cefpython.md#getbrowserbywindowhandle)
159159
* [GetCommandLineSwitch](cefpython.md#getcommandlineswitch)
160+
* [GetDataUrl](cefpython.md#getdataurl)
160161
* [GetGlobalClientCallback](cefpython.md#getglobalclientcallback)
161162
* [GetModuleDirectory](cefpython.md#getmoduledirectory)
162163
* [GetVersion](cefpython.md#getversion)

api/cefpython.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Table of contents:
1616
* [GetBrowserByIdentifier](#getbrowserbyidentifier)
1717
* [GetBrowserByWindowHandle](#getbrowserbywindowhandle)
1818
* [GetCommandLineSwitch](#getcommandlineswitch)
19+
* [GetDataUrl](#getdataurl)
1920
* [GetGlobalClientCallback](#getglobalclientcallback)
2021
* [GetModuleDirectory](#getmoduledirectory)
2122
* [GetVersion](#getversion)
@@ -140,6 +141,20 @@ Get browser by outer or inner window handle. An outer window handle is the one t
140141
Returns the [CommandLineSwitches](CommandLineSwitches.md) switch that was passed to Initialize(). Returns None if key is not found.
141142

142143

144+
### GetDataUrl
145+
146+
| Parameter | Type |
147+
| --- | --- |
148+
| data | string |
149+
| mediatype="html" (optional) | string |
150+
| __Return__ | object |
151+
152+
Convert data to a Data URL. Only "html" media type is currently supported.
153+
154+
See:
155+
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
156+
157+
143158
### GetGlobalClientCallback
144159

145160
| Parameter | Type |

examples/README-examples.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,17 @@ workarounds.
6767
### Snippets
6868

6969
See small code snippets that test various features in the
70-
[examples/snippets/](snippets/) directory.
70+
[examples/snippets/](snippets/) directory:
71+
72+
- [javascript_bindings.py](snippets/javascript_bindings.py) - Communicate
73+
between Python and Javascript asynchronously using
74+
inter-process messaging with the use of Javascript Bindings.
75+
- [mouse_clicks.py](snippets/mouse_clicks.py) - Perform mouse clicks
76+
and mouse movements programmatically.
77+
- [network_cookies.py](snippets/network_cookies.py) - Implement
78+
interfaces to block or allow cookies over network requests.
79+
- [onbeforeclose.py](snippets/onbeforeclose.py) - Implement interface
80+
to execute custom code before browser window closes.
7181

7282

7383
### Build executable with PyInstaller

examples/pyinstaller/hook-cefpython3.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ def get_cefpython3_datas():
162162
# TODO: Write a tool script that would find such imports in
163163
# .pyx files automatically.
164164
hiddenimports = [
165+
"base64",
165166
"codecs",
166167
"copy",
167168
"datetime",
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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()

examples/snippets/mouse_clicks.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ class LifespanHandler(object):
4343
def OnLoadEnd(self, browser, **_):
4444
# Execute function with a delay of 1 second after page
4545
# has completed loading.
46-
print("Page completed loading")
46+
print("Page loading is complete")
4747
cef.PostDelayedTask(cef.TID_UI, 1000, click_after_1_second, browser)
4848

4949

examples/snippets/network_cookies.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def CanGetCookies(self, frame, request, **_):
3030
print("-- CanGetCookies #"+str(self.getcount))
3131
print("url="+request.GetUrl()[0:80])
3232
print("")
33-
# Return True to allow reading cookies and False to block
33+
# Return True to allow reading cookies or False to block
3434
return True
3535

3636
def CanSetCookie(self, frame, request, cookie, **_):
@@ -43,7 +43,7 @@ def CanSetCookie(self, frame, request, cookie, **_):
4343
print("Name="+cookie.GetName())
4444
print("Value="+cookie.GetValue())
4545
print("")
46-
# Return True to allow setting cookie and False to block
46+
# Return True to allow setting cookie or False to block
4747
return True
4848

4949

src/cef_v59..v66_changes.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ NEW FEATURES
8282
+ onbeforeclose.py
8383
+ network_cookies.py
8484
+ mouse_clicks.py
85+
+ javascript_bindings.py
86+
+ cef.GetDataUrl
8587

8688
internal/cef_types.h
8789
+ cef_log_severity_t: new key LOGSEVERITY_DEBUG (no need to expose,

src/cefpython.pyx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,8 @@ import datetime
134134
import random
135135
# noinspection PyUnresolvedReferences
136136
import struct
137+
# noinspection PyUnresolvedReferences
138+
import base64
137139

138140
# Must use compile-time condition instead of checking sys.version_info.major
139141
# otherwise results in "ImportError: cannot import name urlencode" strange
@@ -1023,3 +1025,9 @@ cpdef dict GetVersion():
10231025

10241026
cpdef LoadCrlSetsFile(py_string path):
10251027
CefLoadCRLSetsFile(PyToCefStringValue(path))
1028+
1029+
cpdef GetDataUrl(data, mediatype="html"):
1030+
html = data.encode("utf-8", "replace")
1031+
b64 = base64.b64encode(html).decode("utf-8", "replace")
1032+
ret = "data:text/html;base64,{data}".format(data=b64)
1033+
return ret

0 commit comments

Comments
 (0)