micropython.js how to run on webpage

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
DJShadow1966
Posts: 60
Joined: Sun Jun 23, 2019 4:55 am
Location: Gateshead, Tyne and Wear

micropython.js how to run on webpage

Post by DJShadow1966 » Mon Jan 27, 2020 9:36 am

Hello

U am trying to get the micropython.js to run in a webpage, I have followed the instructions to build the .js file and that works in node with no issues.

Using the html code from the git repo I am only getting a blank page, nothing inside of it ?

Code: Select all

<!doctype html>
<html>
  <head>
    <script src="/home/sysadmin/micropython/ports/javascript/build/micropython.js"></script>
  </head>
  <body>
    <div id='mp_js_stdout'></div>
    <script>
      mp_js_stdout.addEventListener('print', function(e) {
        document.write(e.data);
      }, false);

      mp_js_init(64 * 1024);
      mp_js_do_str('print(\'hello world\')');
    </script>
  </body>
</html>
Pretty much lost from there.

Regards Mike

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: micropython.js how to run on webpage

Post by jimmo » Mon Feb 03, 2020 3:11 am

DJShadow1966 wrote:
Mon Jan 27, 2020 9:36 am
Using the html code from the git repo I am only getting a blank page, nothing inside of it ?
Hi,

I took a quick look at this, was able to get it working with the following changes:

1. It was failing to load the resources from the filesystem. Solution is to run a local webserver (i.e. python3 -m http.server) then access it as http://localhost:8000/demo.html

2. I don't quite understand how the demo example ever worked. Either way, the following works:

Code: Select all

<!doctype html>
<html>
  <head>
    <script src="build/micropython.js"></script>
  </head>
  <body>
    <pre id="mp_js_stdout"></pre>
    <script>
        setTimeout(function() {
            document.getElementById('mp_js_stdout').addEventListener('print', function(e) {
                document.getElementById('mp_js_stdout').innerText += e.data;
            }, false);

            mp_js_init(64 * 1024);
            mp_js_do_str('print(\'hello world\')');
        }, 1000);
    </script>
  </body>
</html>

DJShadow1966
Posts: 60
Joined: Sun Jun 23, 2019 4:55 am
Location: Gateshead, Tyne and Wear

Re: micropython.js how to run on webpage

Post by DJShadow1966 » Mon Feb 03, 2020 10:24 am

Hello

Many thanks for that, didn't need to run a python webserver as already running apache so all I need to now do is build the actal page, working on this tomorrow.

Regards Mike

Post Reply