0

Is there a way to send data packets from an active Python script to a webpage currently running JavaScript?

The specific usage I'm looking for is to give the ability for the webpage, using JavaScript, to tell the Python script information about the current state of the webpage, then for the Python script to interpret that data and then send data back to the webpage, which the JavaScript then uses to decide which function to execute.

This is for a video game bot (legally), so it would need to happen in real time. I'm fairly proficient in Python and web requests, but I'm just getting into JavaScript, so hopefully a solution for this wouldn't be too complex in terms of Javascript.

EDIT: One way I was thinking to accomplish this would be to have Javascript write to a file that the Python script could also read and write to, but a quick google search says that JavaScript is very limited in terms of file I/O. Would there be a way to accomplish this?

2

3 Answers 3

0

For security reasons, javascript in a browser is usually restricted to only communicate with the site it was loaded from.

Given that, that's an AJAX call, a very standard thing to do.

1
  • An AJAX call? Could you elaborate? Apr 8, 2014 at 23:52
0

You can make HTTP requests using the XMLHttpRequest API, which Jquery abstracts with $.ajax and $.get. You can also use the lower level Websockets network API:

https://developer.mozilla.org/en-US/docs/WebSockets

Note that the XMLHttpRequest API will only allow requests to the same server, OR requests that return an appropriate Access-Control-Allow-Origin header.

0

It sounds like the Javascript is only going to send information, not receive any. In that case, you're in luck. I'm guessing you are also running the Javascript and the Python on the same machine.

Run a Python webserver on the machine the browser is running on. Here's a simple example:

http://webpy.org/install

Once visiting http://127.0.0.1:8080/ in your browser gives the message Hello World!, you can start adding more addresses to your website, for example http://127.0.0.1:8080/report_data, http://127.0.0.1:8080/report_event etc.

Your Javascript can then make AJAX requests using jQuery.ajax or XMLHTTPRequest, to the address http://127.0.0.1:8080/report_data, and pass the information as GET parameters.

2
  • Sorry, that's inaccurate. I need Python to be able to send information to JavaScript in order for Javascript to execute functions based on the information that Python processed. Apr 9, 2014 at 1:32
  • Then you can encode the data in Python using json.dumps, and add the Access-Control-Allow-Origin header to the response using web.header, and in the browser, use JSON.parse to read the response.
    – r3m0t
    Apr 9, 2014 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.