Safari : LiveView don't work in iframe, websocket error

Hi everyone,

I’m resurrecting a problem that has already been raised, but how do I get Phoenix Liveview to work in an iframe on Safari?

The problem is: by default Safari blocks cookies from an iframe, which seems to block the Phoenix websocket connection: {response: {reason: "stale"}, status: "error"} . Resulting in a frozen page, even when the iframe works on every other browser.

I found a first piece of solution in a link shared in this old topic (that I did not dare to necropost) → Safari Websocket Connection Problems in iframe - endless reload - #4 by Waschti

This script (from Safari iframe cookie workaround · GitHub 's comments) :

<script>
  // Safari now suddenly blocks iframe cookie access, so we need to call this during some user interaction
  function safariFix() {
    if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
      document.requestStorageAccess().then(() => {
          // Now we have first-party storage access!
          console.log("Got cookie access for Safari workaround");
          // Let's access some items from the first-party cookie jar
          document.cookie = "foo=bar";              // drop a test cookie
        },  () => { console.log('access denied') }).catch((error) => {
          // error obtaining storage access.
          console.log("Could not get access for Safari workaround: " + error);
        });
      }
  }
</script>

Allows you to create a cookie and bypassing the blocking. But I don’t understand how this could allow me to make my websocket work?

Any idea to help me ? Thanks in advance.

I’m not sure about safari, however I remember the webview on android blocking js and http connections by default, may be the case here too.

Just disable cookies. Here is a link how to do it Phoenix and LiveView without cookies - Byteflip

Cookies help manage the session. As stated in the article:

These instructions remove cross-site request forgery protection. Our site is read-only and has no forms. If you have any forms, login area, any url that modifies state on the server - think twice before applying these examples. You probably then do need sessions and cookies.

This therefore hardly applies to Phoenix applications using an iframe to provide functionality on its customers’ websites.

Afaik this is a (known) limitation with safari and using iframes.

But you can disable cookies just for part of application (for page you want to render in iframe). Just create another endpoint for it. You don’t really need session if you are not redirecting within iframe.