Skip to content

Commit

Permalink
Add onpagecomplete.py snippet (#403) and others.
Browse files Browse the repository at this point in the history
Add tools/run_snippets.py.
  • Loading branch information
cztomczak committed Aug 20, 2018
1 parent 6bb2d4e commit 7448372
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 10 deletions.
2 changes: 2 additions & 0 deletions examples/README-examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ See small code snippets that show various CEF features in the
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.
- [onpagecomplete.py](snippets/onpagecomplete.py) - Execute custom
Python code on a web page when page loading is complete.


### GUI frameworks
Expand Down
18 changes: 9 additions & 9 deletions examples/snippets/ondomready.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""
Execute custom Python code on a web page as soon as DOM is ready.
Implements a custom "_OnDomReady" event in the LifespanHandler object.
Implements a custom "_OnDomReady" event in the LoadHandler object.
"""

from cefpython3 import cefpython as cef
Expand All @@ -10,19 +10,19 @@ def main():
cef.Initialize()
browser = cef.CreateBrowserSync(url="https://www.google.com/",
window_title="_OnDomReady event")
lifespan_handler = LifespanHandler(browser)
browser.SetClientHandler(lifespan_handler)
load_handler = LoadHandler(browser)
browser.SetClientHandler(load_handler)
bindings = cef.JavascriptBindings()
bindings.SetFunction("LifespanHandler_OnDomReady",
lifespan_handler["_OnDomReady"])
bindings.SetFunction("LoadHandler_OnDomReady",
load_handler["_OnDomReady"])
browser.SetJavascriptBindings(bindings)
cef.MessageLoop()
del lifespan_handler
del load_handler
del browser
cef.Shutdown()


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

Expand All @@ -32,10 +32,10 @@ def __getitem__(self, key):
def OnLoadStart(self, browser, **_):
browser.ExecuteJavascript("""
if (document.readyState === "complete") {
LifespanHandler_OnDomReady();
LoadHandler_OnDomReady();
} else {
document.addEventListener("DOMContentLoaded", function() {
LifespanHandler_OnDomReady();
LoadHandler_OnDomReady();
});
}
""")
Expand Down
35 changes: 35 additions & 0 deletions examples/snippets/onpagecomplete.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
Execute custom Python code on a web page when page loading is complete.
Implements a custom "_OnPageComplete" event in the LoadHandler object.
"""

from cefpython3 import cefpython as cef


def main():
cef.Initialize()
browser = cef.CreateBrowserSync(url="https://www.google.com/",
window_title="_OnPageComplete event")
browser.SetClientHandler(LoadHandler())
cef.MessageLoop()
del browser
cef.Shutdown()


class LoadHandler(object):
def OnLoadingStateChange(self, browser, is_loading, **_):
"""For detecting if page loading has ended it is recommended
to use OnLoadingStateChange which is most reliable. The OnLoadEnd
callback also available in LoadHandler can sometimes fail in
some cases e.g. when image loading hangs."""
if not is_loading:
self._OnPageComplete(browser)

def _OnPageComplete(self, browser):
print("Page loading is complete!")
browser.ExecuteFunction("alert", "Message from Python: Page loading"
" is complete!")


if __name__ == '__main__':
main()
1 change: 1 addition & 0 deletions src/cef_v59..v66_changes.txt
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ NEW FEATURES
+ javascript_bindings.py
+ javascript_errors.py
+ ondomready.py
+ onpagecomplete
+ cef.GetDataUrl

internal/cef_types.h
Expand Down
1 change: 1 addition & 0 deletions tools/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@
# -- end build directories

EXAMPLES_DIR = os.path.join(ROOT_DIR, "examples")
SNIPPETS_DIR = os.path.join(EXAMPLES_DIR, "snippets")
SRC_DIR = os.path.join(ROOT_DIR, "src")

# Subdirectories in src/
Expand Down
3 changes: 2 additions & 1 deletion tools/run_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
# Project website: https://github.com/cztomczak/cefpython

"""
Run all examples that can be run on current configuration.
Run all examples that can be run on current configuration
and display a summary at the end.
Note on GTK 2 / GTK 3 on Windows:
Installing both PyGTK and PyGI on Windows will cause errors.
Expand Down
55 changes: 55 additions & 0 deletions tools/run_snippets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Copyright (c) 2018 CEF Python, see the Authors file.
# All rights reserved. Licensed under BSD 3-clause license.
# Project website: https://github.com/cztomczak/cefpython

"""
Run all snippets from the examples/snippets/ directory
and display a summary at the end.
"""

from common import *

import glob
import os
import subprocess
import sys


def main():
# Iterate over all snippets
snippets_iter = glob.glob(os.path.join(SNIPPETS_DIR, "*.py"))
succeeded = []
failed = []
for snippet in snippets_iter:
print("[run_snippets.py] Running '{snippet}'..."
.format(snippet=os.path.basename(snippet)))
retcode = subprocess.call([sys.executable, snippet])
if retcode == 0:
succeeded.append(os.path.basename(snippet))
else:
print("[run_snippets.py] ERROR while running snippet: {snippet}"
.format(snippet=snippet))
failed.append(os.path.basename(snippet))

# Print summary
summary = ""
for snippet in succeeded:
summary += " OK {snippet}{nl}"\
.format(snippet=snippet, nl=os.linesep)
for snippet in failed:
summary += " ERROR {snippet}{nl}"\
.format(snippet=snippet, nl=os.linesep)
summary = summary[:-(len(os.linesep))]
print("[run_snippets.py] SUMMARY:")
print(summary.format())
if len(failed):
print("[run_snippets.py] ERRORS ({failed}) while running snippets"
.format(failed=len(failed)))
sys.exit(1)
else:
print("[run_snippets.py] OK ({succeeded})"
.format(succeeded=len(succeeded)))


if __name__ == "__main__":
main()

0 comments on commit 7448372

Please sign in to comment.