Skip to content

Ports

Ports provide interop between javascript and your Gren program.

To start using ports, you’ll need a program defined with Browser.element, Browser.document, or Browser.application.

Change your module to a port module:

src/Main.gren
module Main exposing (main)
port module Main exposing (main)

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.

src/Main.gren
port toJs : String -> Cmd msg
port fromJs : (String -> msg) -> Sub msg

Use commands to send outgoing messages:

src/Main.gren
init : {} -> { model : Model, command : Cmd Msg }
init _ =
{ model = { message = "" }
, command = toJs "Hello from Gren!"
}

Use subscriptions to receive incoming messages:

src/Main.gren
type Msg
= MessageReceived String
update : Msg -> Model -> { model : Model, command : Cmd Msg }
update msg model =
when msg is
MessageReceived message ->
{ model = { model | message = message }
, command = Cmd.none
}
subscriptions : Model -> Sub Msg
subscriptions _ =
fromJs MessageReceived

Compile your program to a javascript file:

Terminal window
gren make src/Main.gren --output=main.js

Create an html file that starts your program like this:

<html>
<head>
<script src="main.js"></script>
</head>
<body>
<div id="myapp"></div>
<script>
var app = Gren.Main.init({
node: document.getElementById('myapp'),
});
// receiving messages from gren:
app.ports.toJs.subscribe(function(message) {
alert(message);
});
// sending messages to gren:
app.ports.fromJs.send("Hello from JS!");
</script>
</body>
</html>