import sys
from PySide2.QtCore import QObject, QUrl, Signal, Slot
from PySide2.QtWidgets import QApplication
from PySide2.QtWebChannel import QWebChannel
from PySide2.QtWebEngineWidgets import QWebEngineView


html = """
<!DOCTYPE html>
<html lang="en">
<head>
<title>Benten</title>

<script src="qrc:/qtwebchannel/qwebchannel.js" type="text/javascript"></script>

<script>
document.addEventListener("DOMContentLoaded", function () {

    'use strict';

    new QWebChannel(qt.webChannelTransport, function(channel) {

        var talkie = channel.objects.talkie;

        talkie.send_text_js_side.connect(function(text) {
            alert(text)
        })

        talkie.send_list_js_side.connect(function(list) {
            alert(list[0])
        })

    });

});
</script>

</head>
<body>

</body>
</html>"""


class TalkyTalky(QObject):
    send_text_js_side = Signal(str)
    send_list_js_side = Signal(list)

    def __init__(self, parent=None):
        super().__init__(parent)


if __name__ == '__main__':
    app = QApplication(sys.argv)

    view = QWebEngineView()
    page = view.page()

    talkie = TalkyTalky()


    def foo():
        channel = QWebChannel(page)
        channel.registerObject("talkie", talkie)

        page.setWebChannel(channel)
        page.setHtml(html, QUrl("qrc:/index.html"))


    foo()
    view.show()

    from PySide2.QtCore import QTimer

    timer = QTimer()
    timer.setSingleShot(True)
    timer.setInterval(1000)
    timer.timeout.connect(lambda x=None: talkie.send_text_js_side.emit("Hello from Python!"))
    timer.start()

    timer2 = QTimer()
    timer2.setSingleShot(True)
    timer2.setInterval(5000)
    timer2.timeout.connect(lambda x=None: talkie.send_list_js_side.emit(["Hello from Python list!"]))
    timer2.start()

    # -> leads to js: Uncaught TypeError: Cannot read property '0' of null

    app.exec_()
