Skip to content

Commit

Permalink
Add javascript_erors.py and ondomready.py snippets (#403)
Browse files Browse the repository at this point in the history
  • Loading branch information
cztomczak committed Aug 20, 2018
1 parent 2415a8f commit 6bb2d4e
Show file tree
Hide file tree
Showing 6 changed files with 140 additions and 20 deletions.
3 changes: 2 additions & 1 deletion docs/Tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ basics. This tutorial will discuss the three featured examples:
[hello_world.py](../examples/hello_world.py),
[tutorial.py](../examples/tutorial.py)
and [screenshot.py](../examples/screenshot.py). There are many
more examples that you can find in the [README-examples.md](../examples/README-examples.md)
more examples that you can find in the
[README-examples.md](../examples/README-examples.md)
file, but these examples are out of scope for this tutorial.


Expand Down
41 changes: 24 additions & 17 deletions examples/README-examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ Table of contents:
* [Hello World!](#hello-world)
* [Supported examples](#supported-examples)
* [Featured](#featured)
* [GUI frameworks](#gui-frameworks)
* [Snippets](#snippets)
* [GUI frameworks](#gui-frameworks)
* [Build executable with PyInstaller](#build-executable-with-pyinstaller)
* [Unit tests](#unit-tests)
* [Other examples](#other-examples)
Expand Down Expand Up @@ -42,8 +42,31 @@ workarounds.
discussed in great details in Tutorial in the [Off-screen rendering](../docs/Tutorial.md#off-screen-rendering)
section.


### Snippets

See small code snippets that show various CEF features in the
[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.
- [javascript_errors.py](snippets/javascript_errors.py) - Two ways for
intercepting Javascript errors.
- [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.
- [ondomready.py](snippets/ondomready.py) - Execute custom Python code
on a web page as soon as DOM is ready.


### GUI frameworks

Examples of embedding CEF browser using various GUI frameworks:

- [gtk2.py](gtk2.py): example for [PyGTK](http://www.pygtk.org/)
library (GTK 2)
- [gtk3.py](gtk3.py): example for [PyGObject / PyGI](https://wiki.gnome.org/Projects/PyGObject)
Expand All @@ -64,22 +87,6 @@ workarounds.
toolkit. This example implements High DPI support on Windows.


### Snippets

See small code snippets that test various features in the
[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

- [PyInstaller example](pyinstaller/README-pyinstaller.md):
Expand Down
3 changes: 1 addition & 2 deletions examples/snippets/javascript_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
</style>
<script>
function print(msg) {
console.log(msg+" [JS]");
document.getElementById("console").innerHTML += msg+"<br>";
}
function js_function(value) {
Expand All @@ -41,7 +40,7 @@
def main():
cef.Initialize()
browser = cef.CreateBrowserSync(url=cef.GetDataUrl(g_htmlcode),
window_title="OnBeforeClose")
window_title="Javascript Bindings")
browser.SetClientHandler(LifespanHandler())
bindings = cef.JavascriptBindings()
bindings.SetFunction("py_function", py_function)
Expand Down
61 changes: 61 additions & 0 deletions examples/snippets/javascript_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""
Two ways for intercepting Javascript errors:
1. window.onerror event in Javascript
2. DisplayHandler.OnConsoleMessage in Python
"""

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) {
document.getElementById("console").innerHTML += msg+"<br>";
}
window.onerror = function(message, source, lineno, colno, error) {
print("[JS:window.onerror] "+error+" (line "+lineno+")");
// Return false so that default event handler is fired and
// OnConsoleMessage can also intercept this error.
return false;
};
window.onload = function() {
forceError();
};
</script>
</head>
<body>
<h1>Javascript Errors</h1>
<div id=console></div>
</body>
</html>
"""


def main():
cef.Initialize()
browser = cef.CreateBrowserSync(url=cef.GetDataUrl(g_htmlcode),
window_title="Javascript Errors")
browser.SetClientHandler(DisplayHandler())
cef.MessageLoop()
cef.Shutdown()


class DisplayHandler(object):
def OnConsoleMessage(self, browser, message, line, **_):
if "error" in message.lower() or "uncaught" in message.lower():
logmsg = "[Py:OnConsoleMessage] {message} (line {line})" \
.format(message=message, line=line)
print(logmsg)
browser.ExecuteFunction("print", logmsg)


if __name__ == '__main__':
main()
50 changes: 50 additions & 0 deletions examples/snippets/ondomready.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""
Execute custom Python code on a web page as soon as DOM is ready.
Implements a custom "_OnDomReady" event in the LifespanHandler object.
"""

from cefpython3 import cefpython as cef


def main():
cef.Initialize()
browser = cef.CreateBrowserSync(url="https://www.google.com/",
window_title="_OnDomReady event")
lifespan_handler = LifespanHandler(browser)
browser.SetClientHandler(lifespan_handler)
bindings = cef.JavascriptBindings()
bindings.SetFunction("LifespanHandler_OnDomReady",
lifespan_handler["_OnDomReady"])
browser.SetJavascriptBindings(bindings)
cef.MessageLoop()
del lifespan_handler
del browser
cef.Shutdown()


class LifespanHandler(object):
def __init__(self, browser):
self.browser = browser

def __getitem__(self, key):
return getattr(self, key)

def OnLoadStart(self, browser, **_):
browser.ExecuteJavascript("""
if (document.readyState === "complete") {
LifespanHandler_OnDomReady();
} else {
document.addEventListener("DOMContentLoaded", function() {
LifespanHandler_OnDomReady();
});
}
""")

def _OnDomReady(self):
print("DOM is ready!")
self.browser.ExecuteFunction("alert",
"Message from Python: DOM is ready!")


if __name__ == '__main__':
main()
2 changes: 2 additions & 0 deletions src/cef_v59..v66_changes.txt
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ NEW FEATURES
+ network_cookies.py
+ mouse_clicks.py
+ javascript_bindings.py
+ javascript_errors.py
+ ondomready.py
+ cef.GetDataUrl

internal/cef_types.h
Expand Down

0 comments on commit 6bb2d4e

Please sign in to comment.