JavaScript Interop

    But what happens when you need to integrate with JavaScript? Maybe there is a browser API that does not have an equivalent Elm package yet. Maybe you want to embed a JavaScript widget within your Elm app? Etc. This chapter will outline Elm’s three interop mechanisms:

    Before we get into the three mechanisms, we need know how to compile Elm programs to JavaScript!

    It produces an index.html file that you can just open and start playing with. If you are getting into JavaScript interop, you want to produce JavaScript files instead:

    This produces a JavaScript file that exposes an Elm.Main.init() function. So once you have main.js you can write your own HTML file that does whatever you want.

    Embedding in HTML

    Here is the minimal HTML needed to make your main.js appear in a browser:

    • <body> - We need to do two things here. First, we create a that want our Elm program to take over. Maybe it is within a larger application, surrounded by tons of other stuff? That is fine! Second, we have a <script> to initializes our Elm program. Here we call the Elm.Main.init() function to start our program, passing in the node we want to take over.

    Now that we know how to embed Elm programs in an HTML document, it is time to start exploring the three interop options: flags, ports, and custom elements!