Hi everyone,
I have to integrate a Facebook pixel script on the confirmation button of a contact form => Weiterführend - Facebook-Pixel - Dokumentation - Facebook for Developers
I’m not sure what the correct way to do with Phoenix Liveview is. Is there already a way to use Pixel with Elixir? Should I use JS interoperability JavaScript interoperability — Phoenix LiveView v0.17.5 (but I had difficulty figuring out how it works)?
If any of you have already made the integration of Facebook Pixel on a project or something similar, I admit that a concrete example would help me a lot 
Thanks for your time.
1 Like
You’ll want to use JS Hooks: JavaScript interoperability — Phoenix LiveView v0.17.5 (that link has a target attached).
In short:
// assets/js/app.js
const Hooks = {};
Hooks.FacebookPixel = {
mounted() {
// add fb pixel code here
}
}
// Update the `let liveSocket =` line to add hooks:
let liveSocket = new LiveSocket("/live", Socket, {
params: {
_csrf_token: csrfToken,
hooks: Hooks // <- Add hooks!
}
})
Now somewhere in your DOM:
def render(assigns) do
~H"""
<div phx-hook="FacebookPixel">
<!-- more heex -->
</div>
"""
end
Note: When adding hooks that create DOM event listeners, you’ll want to make sure that you attach it to a node that doesn’t get re-rendered or else you’ll have to be defensive in your JS code to ensure the listener doesn’t get created over and over. I don’t have good example of the latter, I just do the former.
3 Likes
Thank you a lot for your help !
1 Like