0

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.

Ryan
  • 5,883
  • 13
  • 56
  • 93
  • Why are you trying to do that ? Are you in a web server environment like Django or Flask ? – Louis-Justin Tallot Jul 07 '21 at 11:16
  • It is impossible to call a function in browser from the python script. You can do an http request from JS to the server which calls the python code and returns the result. – Никита Нигматуллин Jul 07 '21 at 11:16
  • 1
    You _could_ use python to click a button in the page, or to communicate with the browser over a websocket. You can't use python to directly call that function. – Cerbrus Jul 07 '21 at 11:18
  • 1
    as @Cerbrus said, look into websockets. In particular socket.io, which has clients both for the python and javascript side of things. Websockets allow you to create bi-directional communication between a server and a website. – Hoff Jul 07 '21 at 11:19
  • 1
    You can operate your browser to open a webpage and call JavaScript from python on that page, if that's what you want to do. See [this question](https://stackoverflow.com/questions/7794087/running-javascript-in-selenium-using-python). – daylily Jul 07 '21 at 11:20
  • 1
    I built a game on a webpage that humans can play. I want to create a Python bot that can trigger the JavaScript functions on the webpage and thus "play" the game. – Ryan Jul 07 '21 at 11:25
  • 1
    Then using websockets would be your best option I think. That said, that does mean your JS game would need to start sending out all the relevant events. – Cerbrus Jul 07 '21 at 11:29
  • To clarify, the game already has a Python back-end and that Python back-end accepts WebSocket connections from the front-end. But this existing Python back-end has nothing to do with what I'm talking about here. Instead, I need to run a "normal" or "local" Python script that communicates with my local instance of a browser. So it sounds like I need to set up a second Python WebSocket server specifically for the bot communication. It seems like the browser would initiate a connection to this second server just like the first. – Ryan Jul 07 '21 at 14:35

2 Answers2

0

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?.

0

Hi so one possible solution would be to use ajax with flask to comunicate between javascript and python. You would run a server with flask and then open the website in a browser. This way you could run javascript functions when the website is created via pythoncode or with a button how it is done in this example.

in getJSON the function argument receives the result of the python function. here you could run js code depending on the output and run your function foo(z) as an if condition

also with flask you determine which js code you want to show to your client.

HTML code:



<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


<script>
    function pycall() {
      $.getJSON('/pycall', {content: "content from js"},function(data) {
          //run here your function on if(data.result==0) for example
          alert(data.result);
      });
    }
</script>


<button type="button" onclick="pycall()">click me</button>
 

</html>

Python Code:

from flask import Flask, jsonify, render_template, request

app = Flask(__name__)


def load_file(file_name):
    data = None
    with open(file_name, 'r') as file:
        data = file.read()
    return data

@app.route('/pycall')
def pycall():
    content = request.args.get('content', 0, type=str)
    
    print("call_received",content)
    return jsonify(result="data from python")

@app.route('/')
def index():
    return load_file("basic.html")



import webbrowser
print("opening localhost")
url = "http://127.0.0.1:5000/"
webbrowser.open(url)
app.run()

output in python:

call_received content from js

alert in browser:

data from python

rtuiiop
  • 11
  • 4