Cef示例

cefpython

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
54
55
import base64
import sys

from cefpython3 import cefpython as cef

html = """
<html lang="zh" style="height: 100%">
<head>
<link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.css" rel="stylesheet">
<title></title>
</head>
<body class="d-flex flex-column align-items-center justify-content-center" style="height: 100%;">
<span class="h3 text-primary">Python version:</span>
<span class="h4 text-info" id="version">unknown</span>
<!--suppress JSUnresolvedVariable, JSUnresolvedFunction -->
<script>
function setPythonVersion(version) {
document.getElementById("version").innerText=version;
}
document.addEventListener("DOMContentLoaded", ()=>{
bridge.onLoaded()
})
</script>
</body>
</html>
"""


def generate_data_uri(html):
encoded = base64.b64encode(html.encode("utf8")).decode("utf8")
return f"data:text/html;base64,{encoded}"


def main():
cef.DpiAware.EnableHighDpiSupport()
cef.Initialize()
browser: cef.PyBrowser = cef.CreateBrowserSync()
cef.WindowUtils.SetTitle(browser, "OK")
browser.LoadUrl(generate_data_uri(html))

# noinspection PyMethodMayBeStatic,PyPep8Naming
class Bridge(object):
def onLoaded(self):
browser.ExecuteFunction("setPythonVersion", sys.version)

bridge = Bridge()
bindings = cef.JavascriptBindings(bindToFrames=False, bindToPopups=False)
bindings.SetObject("bridge", bridge)
browser.SetJavascriptBindings(bindings)

cef.MessageLoop()


if __name__ == '__main__':
main()

文章首发: https://baijifeilong.github.io