Search code examples
javascriptpythonlanguage-binding

Use Python to call a JavaScript function that is on a webpage


I created a webpage that has one JavaScript function called foo(z). For the sake of this question, let's assume that all foo(z) does is call console.log(z).

Is it possible to run a Python script that can trigger the JavaScript foo(z) function that exists on the webpage?

In other words, I load up the webpage in my browser that contains foo(z). Then I execute the Python script on my local machine and it reaches into the browser and calls the JavaScript foo(z) function and you thus see z output to the browser console (because all foo(z) does is call console.log(z)).

It seems like there is a lot of info on executing JavaScript with Python, but I don't think any of those resources deal with executing a JavaScript function that is inside a webpage.

Edit: I built a game on a webpage that humans can play. Now I want to create a Python bot that can call the JavaScript functions on the webpage so that it too can play the game.


Solution

  • You cannot directly execute the javascript from python.

    If you are running a local server, you can communicate with the page using a websocket and make it execute the JS function when the python page emits a signal to do so. The Flask framework can be useful.

    You can also see this question : How do I call a Javascript function from Python?.