Javascript Interop
Javascript interaction happens through something called ports, which are boundaries that you define between your Gren program, where the compiler can guarantee safety and correctness, and Javascript, where it can’t.
Browser Ports
To start using ports in the browser, you’ll need a program defined with
Browser.element
,
Browser.document
, or
Browser.application
.
Change your module to a port module
:
Define your incoming and outgoing ports.
Here we’re using String
as the data exchange format, but you may want to use JSON for more power and control.
See Json.Decode
and Json.Encode
.
Use commands to send outgoing messages:
Use subscriptions to receive incoming messages:
Compile your program to a javascript file:
Create an html file that starts your program like this:
Node Ports
To use ports in a node program, you’ll need to define it with
Node.defineProgram
like we did in the webserver section of the book.
Then define and use your ports in Gren the same way as described in the browser section above.
Then compile it with an explicit output target:
Giving the target a .js
extension tells the compiler that you want a module to be included in other javascript instead of a program that runs directly.
That lets us wire up the ports in a new Javascript file that looks like this:
Now you can run it with node: