You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJs 12中如何根据路由locale切换OneTrust Cookie横幅语言

在Next.js 12中为/es路由配置西班牙语OneTrust Cookie横幅

解决方案分两步:服务器端初始化+客户端路由切换处理

1. 服务器端渲染时动态设置语言(修改_document.ts)

在_document.ts中通过getInitialProps获取当前请求路径,判断是否为西班牙语路由,然后给OneTrust脚本添加语言属性并初始化对应配置:

import Document, { Html, Head, Main, NextScript } from 'next/document';
import Script from 'next/script';
import Favicon from '../components/Favicon'; // 替换为你的Favicon组件路径

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    // 获取当前请求的URL路径
    const pathname = ctx.req?.url || '';
    // 判断是否为西班牙语路由
    const isSpanish = pathname.startsWith('/es');
    return { ...initialProps, isSpanish };
  }

  render() {
    const { isSpanish } = this.props;
    const cookieLanguage = isSpanish ? 'es' : 'en';

    return (
      <Html>
        <Head>
          <Script
            id="one-trust"
            strategy="beforeInteractive"
            src="https://cdn.cookielaw.org/scripttemplates/otSDKStub.js"
            data-domain-script="xxx"
            // 动态设置OneTrust语言属性
            data-language={cookieLanguage}
          />
          <Script id="one-trust-optanonWrapper" type="text/javascript">
            {`
              function OptanonWrapper() {
                // 强制指定初始化语言
                if (window.Optanon) {
                  Optanon.SetLanguage("${cookieLanguage}");
                }
              }
            `}
          </Script>
          <Favicon />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

2. 客户端路由跳转时动态切换语言(修改_app.tsx)

由于Next.js客户端路由跳转不会重新渲染_document,需要在_app.tsx中监听路由变化,实时更新OneTrust语言:

import { useEffect } from 'react';
import { useRouter } from 'next/router';
import type { AppProps } from 'next/app';

function MyApp({ Component, pageProps }: AppProps) {
  const router = useRouter();

  useEffect(() => {
    const updateCookieBannerLanguage = (url: string) => {
      const isSpanish = url.startsWith('/es');
      const targetLang = isSpanish ? 'es' : 'en';

      // 确保OneTrust对象已加载
      if (window.Optanon) {
        window.Optanon.SetLanguage(targetLang);
        // 若需要在语言切换后重新显示横幅,可取消下方注释
        // Optanon.ToggleDisplay();
      }
    };

    // 监听路由切换完成事件
    router.events.on('routeChangeComplete', updateCookieBannerLanguage);

    // 页面初始加载时设置一次语言
    updateCookieBannerLanguage(router.pathname);

    // 组件卸载时移除监听
    return () => {
      router.events.off('routeChangeComplete', updateCookieBannerLanguage);
    };
  }, [router]);

  return <Component {...pageProps} />;
}

export default MyApp;

关键说明

  • 需确保你已在OneTrust后台完成西班牙语配置(包括语言包、横幅文本翻译等)。
  • data-language是OneTrust官方支持的语言指定方式,会优先加载对应语言的配置资源。
  • Optanon.SetLanguage()方法用于动态切换已加载的横幅语言,适配客户端路由跳转场景。

内容的提问来源于stack exchange,提问作者seven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 08:03:21