forked from cztomczak/cefpython
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathondomready.py
More file actions
53 lines (43 loc) · 1.59 KB
/
Copy pathondomready.py
File metadata and controls
53 lines (43 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
Execute custom Python code on a web page as soon as DOM is ready.
Implements a custom "_OnDomReady" event using the OnContextCreated callback.
"""
from cefpython3 import cefpython as cef
def main():
cef.Initialize()
browser = cef.CreateBrowserSync(url="https://example.com/",
window_title="_OnDomReady event")
handler = DomReadyHandler(browser)
browser.SetClientHandler(handler)
bindings = cef.JavascriptBindings()
bindings.SetFunction("LoadHandler_OnDomReady",
handler["_OnDomReady"])
browser.SetJavascriptBindings(bindings)
cef.MessageLoop()
del handler
del browser
cef.Shutdown()
class DomReadyHandler(object):
def __init__(self, browser):
self.browser = browser
def __getitem__(self, key):
return getattr(self, key)
def OnContextCreated(self, browser, frame, **_):
if not frame.IsMain():
return
browser.ExecuteJavascript("""
if (document.readyState === "complete"
|| document.readyState === "interactive") {
setTimeout(function(){ LoadHandler_OnDomReady(); }, 0);
} else {
document.addEventListener("DOMContentLoaded", function() {
setTimeout(function(){ LoadHandler_OnDomReady(); }, 0);
});
}
""")
def _OnDomReady(self):
print("DOM is ready!")
self.browser.ExecuteFunction("alert",
"Message from Python: DOM is ready!")
if __name__ == '__main__':
main()