Python and JavaScript – Integration for Offline Use

javascriptpythonuser interface

I'm a first timer here so let me know if I should post this question in a different forum!

I have a python program that takes in user input but is only useful when you're offline, I wanted to make the ui better so I thought using HTML CSS, and JavaScript would be perfect. So my question is, is it possible for python and JavaScript to communicate variables between each other when offline(JS front end, python back end)?

Another way to think about it is like how you can choose a script to run on a form submission (but as far as I know this only works if the script is on a server).

Any help would be much appreciated!

Best Answer

A web site is sandboxed and cannot execute any external scripts – it is confined to the browser. But it can issue HTTP requests to a server. A server is not necessarily “a machine in some data center”, but more generally “any process that listens on some port and speaks HTTP”.

Because the JavaScript in the browser sandbox and the Python code can only communicate if the JS sends a HTTP request to a web server that then runs the Python code, you need a server. It is very easy to create a simple Python web server, e.g. with frameworks like Flask. They don't share variables, but they can transfer messages. The message then includes any necessary data. Often, the JS code would send an Ajax POST request with JSON-encoded data, and the server responds with another JSON document that contains the results.

But how can that work without an internet connection? It is possible to run the server on the same computer as the browser. The server then listens on localhost, and no real network requests are made. For example, when I develop a site with static HTML files I often start a simple server with python3 -m http.server -b localhost 8080. I can connect to the server by navigating to http://localhost:8080/ in my browser.

Instead of a static file server, you would run your Python server on some port. Your users would then install your Python software and launch the server, then open the correct address in the browser to load the GUI.

Related Topic