python-eel / Eel

A little Python library for making simple Electron-like HTML/JS GUI apps
MIT License
6.44k stars 587 forks source link

Call Javascript function from inside a Python function using Eel #438

Closed andre-kotze closed 3 years ago

andre-kotze commented 3 years ago

I am having trouble calling a js function from python. The call in python is inside another function, and using the example Eello World files I can reproduce the issue.

The normal call works [ eel.say_hello_js() in python ], but inside a larger function it isn't executed. Is there a way around this?

The .html (from Eello World example)

<html>
  <head>
    <title>Hello, World!</title>
    <script type="text/javascript" src="/eel.js"></script>
    <script type="text/javascript">
      eel.expose(say_hello_js); // Expose this function to Python
      function say_hello_js(x) {
        console.log("Hello from " + x);
      }

      say_hello_js("Javascript World!");
      eel.say_hello_py("Javascript World!"); // Call a Python function
    </script>
  </head>
  <body>
    Hello, World!
  </body>
</html>

The .py that works as expected:

import eel
eel.init('web')

@eel.expose                         # Expose this function to Javascript
def say_hello_py(x):
    print('Hello from %s' % x)

say_hello_py('Python World!')
eel.say_hello_js('Python World!')   # Call a Javascript function

eel.start('hello.html')

The .py that does not execute the js function called from python

import eel

eel.init('web')

@eel.expose                         # Expose this function to Javascript
def say_hello_py(x):
    print('Hello from %s' % x)

say_hello_py('Python World!')

def big_function():
    eel.say_hello_js('Python World!')   # Call a Javascript function FROM INSIDE A FUNCTION

eel.start('hello.html')

Output in the second (not working) scenario (browser, pyconsole and devtools console): image

Desktop:

gracyashhh commented 2 years ago

hey @andre-kotze I'm looking to do the exact same calling JS function from Python using eel, can you please let me know how you solved this issue???

andre-kotze commented 2 years ago

Hi @gracyashhh it's very simple. The function has to be called, obviously. After defining big_function, call it just before eel.start My example should have looked like this (just the second last line added):

import eel eel.init('web')

@eel.expose # Expose this function to Javascript def say_hello_py(x): print('Hello from %s' % x)

say_hello_py('Python World!')

def big_function(): eel.say_hello_js('Python World!') # Call a Javascript function FROM INSIDE A FUNCTION # Actually call the function after defining it: *facepalm big_function()

eel.start('hello.html')`

gracyashhh commented 2 years ago

@andre-kotze Thanks a lot man! The thing though was that JS .trigger('click') was very different from .click() for some reason causing websocket error from EEL, here I've stated everything in detail , and my sincere apologies for not updating that I got it fixed 🙂