Recent searches


No recent searches

Zendesk chat disappears on page change - NextJS implementation



Posted Dec 29, 2023

I'm adding zendesk chat script to a NextJS 13 application. When the page change, the <iframe> of the chat is gone. Chat box disappears. How can i fix it?

Here is the implementation details:

'use client';

import { useEffect, useState } from 'react';

let zafClient = null;

export function useZafClient() {

  const [client, setClient] = useState(zafClient);

  console.log(zafClient);

  useEffect(() => {

    if (!client && typeof window.ZAFClient !== 'undefined') {

      zafClient = window.ZAFClient.init();

      console.log({ zafClient }, 'init');

      setClient(zafClient);

      if (zafClient) {

        console.log('invoke');

        zafClient.invoke('resize', { width: '100%', height: '200px' });

      }

    }

  }, [client]);

  return client;

}
const ZendeskChat = () => {
  const scriptUrl = 'https://static.zdassets.com/ekr/snippet.js?key=xxxxxxx';
  const scriptId = 'ze-snippet';

  useZafClient();

  return <Script src={scriptUrl} id={scriptId} type="text/javascript" />;
};

export default ZendeskChat;
export default async function RootLayout({ children, params }: LayoutProps) {

  const { locale } = params;

  return (

    <html lang={locale} className={roboto.variable}>

      <body>{children}</body>

      <ZendeskChat />

    </html>

  );

}

in Manifest.json

  "location": {

    "chat": {

      "chat_sidebar": "localhost:3000"

    }

  }

 Thank you!

Best, 

Fandy


0

4

4 comments

image avatar

Brandon (729)

Zendesk LuminaryUser Group LeaderThe Humblident Award - 2021Community Moderator

Hey Frandy,

I'm punching a bit outside my weight class here, but I do know that this is a common challenge when integrating third-party widgets in Single Page Applications (SPAs) like those built with Next.js. Here are some steps to help you resolve this issue:

  1. Preserve Chat State Across Route Changes: In SPAs, navigation between pages doesn't reload the entire page but only updates parts of it. This can cause third-party scripts like Zendesk Chat to lose their state or even disappear. To prevent this, you need to ensure that the Zendesk Chat widget is initialized only once and its state is preserved across route changes.

  2. Managing the Chat Widget on Route Changes: You might need to manage the visibility of the Zendesk chat widget manually. One approach is to hide the widget on route changes and then show it again once the route change is complete. This can be done using the router events from Next.js.

  3. Using next/router for Route Change Detection: Utilize next/router to detect route changes and manage the visibility of the chat widget accordingly. 

Hope this helps!

0


Hi Bradon, 

Thanks for your reply. I'm taking your advice to manage the visibility of the Zendesk chat widget manually with the latest next app router changes (usePathname). 

But I wonder how I can hide and show the widget. In my code, I'm initializing and invoking window.ZAFClient in my useZafClient hook. But it is always undefined even chat widget appears on first page load.

Best, 

Fandy

0


Hello guys, im facing an issue when i cannot add custom data to send to zendesk in my Nextjs project. Please advise
export default async function RootLayout({

  children,

}: Readonly<{

  children: ReactNode;

}>) {

  window.zaf

  return (

    <html lang="en">

      <body className={mulish.className}>

        <script

          // biome-ignore lint/security/noDangerouslySetInnerHtml: <explanation>

          dangerouslySetInnerHTML={{

            __html: `

                (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://sgtm.xcoins.com/hjdtxwnj.js?st='+i+dl+'';f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','W96ZB9J');

              `,

          }}

        />

        <style>

          {`

            .grecaptcha-badge {

              bottom: 80px !important;

            }

            #_cashier_iframe {

                width: 100%;

                height: 100vh !important;

            }

          `}

        </style>

        <AppRouterCacheProvider options={{ key: 'css' }}>

          <NextAppDirEmotionCacheProvider options={{ key: 'css' }}>

            <ClientProviders>

              <div>{children}</div>

            </ClientProviders>

          </NextAppDirEmotionCacheProvider>

        </AppRouterCacheProvider>

      </body>

      <Script

        id="ze-snippet"

        strategy="lazyOnload"

        src="https://static.zdassets.com/ekr/snippet.js?key=453a74c7-06ad-4e74-8e04-df0d7fb4d43a"

      />

      <Script strategy="afterInteractive" id="praxis-cashier-script" src={process.env.NEXT_PUBLIC_PRAXIS_CASHIER_CDN} />

    </html>

  );

}

0


image avatar

Tipene Hughes

Zendesk Developer Advocacy

Hi David,
 
Can you let me know the errors you're seeing when attempting to send the data across. Could you also pinpoint the section of your example that handles the request to Zendesk as I'm not seeing any methods being called from the window.zaf object.
 
Thanks,
 
Tipene

0


Please sign in to leave a comment.

Didn't find what you're looking for?

New post