Making Elm unsafe

A simple trick that will make your JavaScript FFI simpler and much unsafer!

https://www.youtube.com/watch?v=PEZWYXPvmS8

Say we have a nifty addTwo function in JSland we’d like to call. The function simply takes an argument and adds two to it.

It’d be nice if we could do something simple like this:

What a lovely FFI experience!

We’d basically be saying to the compiler “hey, trust me for a while, I got this” and it would gladly accept your request.

While this would be great, it would also be extremely unsafe, so Elm doesn’t allow this and makes you use ports, a safer way of doing FFI, basically doing message passing from Elm to JS and viceversa. So you should do that instead!


But

I wouldn’t have teased you before if you couldn’t do that above.

We can just define a funny jsCall function:

And we can call it as above. This will of course compile, and if we run our app as that, it will enter an infinite loop (jsCall call itself indefinitely).

The only remaining thing remaining thing to do is to go to the compiled file (works both, with and without--optimize), look for the compiled jsCall function, which will probably look something like:

And we just replace its content with

And that’s it! You can now define a window.addTwo = a => a + 2 function that will be called from Elm.

Check a demo using exactly the code in this post here, source here.


Disclaimer: I don’t advocate doing or not doing this, I found it curious, and perhaps useful sometimes, but given that you’re pretty much losing safety while doing this and using a hack that may be removed anytime soon, think twice before diving into something like this.