How to know if Liveview is present on the page?

Hi,

This might be a very silly question but how does one know if liveview is present on the page from the javascript?

My need is pretty simple:

  • I have a landing page (+login + register) built with Phoenix
  • I have an app built with Phoenix LiveView

In both world, I have a responsive navbar which shrink on mobile devices. All items are then collapsed in a list behind an hamburger button. I need some very basic javascript to toggle the list.

What I have done in the app built with Phoenix Liveview: I have used a JS Hook, and it works great on all pages. Here is the code:

export default {
  mounted() {
    this.el.addEventListenner('click', () => {
      const target = this.el.dataset.target;
      const $target = document.getElementById(target);

      this.el.classList.toggle('is-active');
      $target.classList.toggle('is-active');
    });
  }
}

Now the thing is, how do I get that working on the landing page, without Phoenix Liveview?
I’d basically like to import a global page.js file from my main javascript file that execute only if Liveview isn’t present on the page.

I tried socket.isConnected(), but as the connection is async, this always returns false when called just after the DOMContent is loaded.

Any idea?

Thanks in advance.

This is just the first thing that came to my mind, not sure how reliable it is. LiveView sets a container div that has a bunch of info. Maybe you could search for it?

Something like: document.querySelector("[data-phx-root-id]")

This is just an idea more than anything.

It seems that data-phx-root-id is generated client side by the liveview JS library.
I used document.querySelector("[data-phx-main]") instead which is sent by the server.

I wonder if that should be part of the liveview JS API? ie. an easy way to know if the page has a liveview or not.

1 Like