Search code examples
javascriptpythonpromisebrython

How to call brython/python from javascript?


I am trying to call brython function from javascript promise it giving error ReferenceError: brythonListener is not defined how to solve this?

python/brython code

<script type="text/python">
def execute(*args):
    print(str(args))
window.brythonListener=execute
</script>

javascript code

            function(data){
                console.log(data) //till here code works
                brythonListener(data)
            }
        )

what i am missing here?


Solution

  • Reason for the issue ReferenceError: brythonListener is not defined is brythonListener was created after brython was loaded to solve this just reload brython when the js script calling python script

    Brython script

    <script type="text/python">
    from browser import window
    
    def execute(*args):
        print(str(args))
    
    window.brythonListener = execute
    </script>
    

    Js Script which will call brython function

    <Script onload="brython()">
    function(data){
      console.log(data)
      brythonListener(data)
    })
    </script>