白季飞龙的个人主页

Cef示例

cefpython

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


漫漫路,莫论逍遥;潜心修,只为悟道