Skip to content

Commit

Permalink
Add javascript_bindings.py snippet (cztomczak#403) and others.
Browse files Browse the repository at this point in the history
Add cef.GetDataUrl().
Update README-examples.md - add Snippets section.
Update PyInstaller example.
  • Loading branch information
cztomczak committed Aug 20, 2018
1 parent 4ba8f58 commit 2415a8f
Show file tree
Hide file tree
Showing 13 changed files with 114 additions and 13 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,7 @@ Additional information for v31.2 release:
* [GetBrowserByIdentifier](api/cefpython.md#getbrowserbyidentifier)
* [GetBrowserByWindowHandle](api/cefpython.md#getbrowserbywindowhandle)
* [GetCommandLineSwitch](api/cefpython.md#getcommandlineswitch)
* [GetDataUrl](api/cefpython.md#getdataurl)
* [GetGlobalClientCallback](api/cefpython.md#getglobalclientcallback)
* [GetModuleDirectory](api/cefpython.md#getmoduledirectory)
* [GetVersion](api/cefpython.md#getversion)
Expand Down
1 change: 1 addition & 0 deletions api/API-index.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@
* [GetBrowserByIdentifier](cefpython.md#getbrowserbyidentifier)
* [GetBrowserByWindowHandle](cefpython.md#getbrowserbywindowhandle)
* [GetCommandLineSwitch](cefpython.md#getcommandlineswitch)
* [GetDataUrl](cefpython.md#getdataurl)
* [GetGlobalClientCallback](cefpython.md#getglobalclientcallback)
* [GetModuleDirectory](cefpython.md#getmoduledirectory)
* [GetVersion](cefpython.md#getversion)
Expand Down
15 changes: 15 additions & 0 deletions api/cefpython.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Table of contents:
* [GetBrowserByIdentifier](#getbrowserbyidentifier)
* [GetBrowserByWindowHandle](#getbrowserbywindowhandle)
* [GetCommandLineSwitch](#getcommandlineswitch)
* [GetDataUrl](#getdataurl)
* [GetGlobalClientCallback](#getglobalclientcallback)
* [GetModuleDirectory](#getmoduledirectory)
* [GetVersion](#getversion)
Expand Down Expand Up @@ -140,6 +141,20 @@ Get browser by outer or inner window handle. An outer window handle is the one t
Returns the [CommandLineSwitches](CommandLineSwitches.md) switch that was passed to Initialize(). Returns None if key is not found.


### GetDataUrl

| Parameter | Type |
| --- | --- |
| data | string |
| mediatype="html" (optional) | string |
| __Return__ | object |

Convert data to a Data URL. Only "html" media type is currently supported.

See:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs


### GetGlobalClientCallback

| Parameter | Type |
Expand Down
12 changes: 11 additions & 1 deletion examples/README-examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,17 @@ workarounds.
### Snippets

See small code snippets that test various features in the
[examples/snippets/](snippets/) directory.
[examples/snippets/](snippets/) directory:

- [javascript_bindings.py](snippets/javascript_bindings.py) - Communicate
between Python and Javascript asynchronously using
inter-process messaging with the use of Javascript Bindings.
- [mouse_clicks.py](snippets/mouse_clicks.py) - Perform mouse clicks
and mouse movements programmatically.
- [network_cookies.py](snippets/network_cookies.py) - Implement
interfaces to block or allow cookies over network requests.
- [onbeforeclose.py](snippets/onbeforeclose.py) - Implement interface
to execute custom code before browser window closes.


### Build executable with PyInstaller
Expand Down
1 change: 1 addition & 0 deletions examples/pyinstaller/hook-cefpython3.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ def get_cefpython3_datas():
# TODO: Write a tool script that would find such imports in
# .pyx files automatically.
hiddenimports = [
"base64",
"codecs",
"copy",
"datetime",
Expand Down
70 changes: 70 additions & 0 deletions examples/snippets/javascript_bindings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""
Communicate between Python and Javascript asynchronously using
inter-process messaging with the use of Javascript Bindings.
"""

from cefpython3 import cefpython as cef

g_htmlcode = """
<!doctype html>
<html>
<head>
<style>
body, html {
font-family: Arial;
font-size: 11pt;
}
</style>
<script>
function print(msg) {
console.log(msg+" [JS]");
document.getElementById("console").innerHTML += msg+"<br>";
}
function js_function(value) {
print("Value sent from Python: <b>"+value+"</b>");
py_function("I am a Javascript string #1", js_callback);
}
function js_callback(value, py_callback) {
print("Value sent from Python: <b>"+value+"</b>");
py_callback("I am a Javascript string #2");
}
</script>
</head>
<body>
<h1>Javascript Bindings</h1>
<div id=console></div>
</body>
</html>
"""


def main():
cef.Initialize()
browser = cef.CreateBrowserSync(url=cef.GetDataUrl(g_htmlcode),
window_title="OnBeforeClose")
browser.SetClientHandler(LifespanHandler())
bindings = cef.JavascriptBindings()
bindings.SetFunction("py_function", py_function)
bindings.SetFunction("py_callback", py_callback)
browser.SetJavascriptBindings(bindings)
cef.MessageLoop()
del browser
cef.Shutdown()


def py_function(value, js_callback):
print("Value sent from Javascript: "+value)
js_callback.Call("I am a Python string #2", py_callback)


def py_callback(value):
print("Value sent from Javascript: "+value)


class LifespanHandler(object):
def OnLoadEnd(self, browser, **_):
browser.ExecuteFunction("js_function", "I am a Python string #1")


if __name__ == '__main__':
main()
2 changes: 1 addition & 1 deletion examples/snippets/mouse_clicks.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ class LifespanHandler(object):
def OnLoadEnd(self, browser, **_):
# Execute function with a delay of 1 second after page
# has completed loading.
print("Page completed loading")
print("Page loading is complete")
cef.PostDelayedTask(cef.TID_UI, 1000, click_after_1_second, browser)


Expand Down
4 changes: 2 additions & 2 deletions examples/snippets/network_cookies.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def CanGetCookies(self, frame, request, **_):
print("-- CanGetCookies #"+str(self.getcount))
print("url="+request.GetUrl()[0:80])
print("")
# Return True to allow reading cookies and False to block
# Return True to allow reading cookies or False to block
return True

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


Expand Down
2 changes: 2 additions & 0 deletions src/cef_v59..v66_changes.txt
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ NEW FEATURES
+ onbeforeclose.py
+ network_cookies.py
+ mouse_clicks.py
+ javascript_bindings.py
+ cef.GetDataUrl

internal/cef_types.h
+ cef_log_severity_t: new key LOGSEVERITY_DEBUG (no need to expose,
Expand Down
8 changes: 8 additions & 0 deletions src/cefpython.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ import datetime
import random
# noinspection PyUnresolvedReferences
import struct
# noinspection PyUnresolvedReferences
import base64

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

cpdef LoadCrlSetsFile(py_string path):
CefLoadCRLSetsFile(PyToCefStringValue(path))

cpdef GetDataUrl(data, mediatype="html"):
html = data.encode("utf-8", "replace")
b64 = base64.b64encode(html).decode("utf-8", "replace")
ret = "data:text/html;base64,{data}".format(data=b64)
return ret
7 changes: 0 additions & 7 deletions unittests/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,6 @@ def show_test_summary(pyfile):
+ os.path.basename(pyfile))


def html_to_data_uri(html):
html = html.encode("utf-8", "replace")
b64 = base64.b64encode(html).decode("utf-8", "replace")
ret = "data:text/html;base64,{data}".format(data=b64)
return ret


def run_message_loop():
# Run message loop for some time.
# noinspection PyTypeChecker
Expand Down
2 changes: 1 addition & 1 deletion unittests/main_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@
</body>
</html>
"""
g_datauri = html_to_data_uri(g_datauri_data)
g_datauri = cef.GetDataUrl(g_datauri_data)


class MainTest_IsolatedTest(unittest.TestCase):
Expand Down
2 changes: 1 addition & 1 deletion unittests/osr_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
</body>
</html>
"""
g_datauri = html_to_data_uri(g_datauri_data)
g_datauri = cef.GetDataUrl(g_datauri_data)


class OsrTest_IsolatedTest(unittest.TestCase):
Expand Down

0 comments on commit 2415a8f

Please sign in to comment.