0

Why am I getting the error

Uncaught ReferenceError: _test() is not defined

in the following source code

<html>
<head>
<meta charset="iso-8859-1">
<script type = "text/javascript" src = "https://cdn.jsdelivr.net/npm/brython@3.8.9/brython.min.js"></script>

<script type="text/python3">
def on_open():
    # Web Socket is connected, send data using send()
    data = doc["data"].value
    if data:
        ws.send(data)
        alert("Message is sent")

def on_message(evt):
    # message received from server
    alert("Message received : %s" %evt.data)

def on_close(evt):
    # websocket is closed
    alert("Connection is closed")

ws = None
def _test():
    global ws
    # open a web socket
    ws = websocket("wss://" + window.location.host + "/test")
    # attach functions to web sockets events
    ws.on_open = on_open
    ws.on_message = on_message
    ws.on_close= on_close

def close_connection():
    ws.close()
</script>
</head>
<body onload="brython()">
<input id="data">
<button onclick="_test()">Run WebSocket</button>
<p><button onclick="close_connection()">Close connection</button>
</body>
</html>

In the following line:

<button onclick="_test()">Run WebSocket</button>
user366312
  • 16,949
  • 65
  • 235
  • 452
  • Not positive, but I think the value of the `onclick` attribute has to be JavaScript; to set a Python callback, you need to go through the DOM in the Python code itself, something like `from browser import document; document["runbutton"].onclick = _test` assuming your button has an `id="runbutton"` attribute. – chepner Feb 10 '23 at 23:21

0 Answers0