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

flip.to提供的函数在Next.js项目中报‘b和e未定义’错,如何改写?

解决Next.js中flip.to脚本“b和e未定义”的问题

问题原因

Next.js默认启用服务端渲染(SSR),原脚本在服务端执行时,window对象不存在,导致立即执行的自执行函数无法获取有效参数,触发“b和e未定义”的错误。

解决方案

方案1:在组件中使用useEffect执行脚本(局部生效)

通过React的useEffect钩子,确保脚本仅在客户端挂载后执行,此时window对象已存在:

import { useEffect } from 'react';

export default function YourTargetPage() {
  useEffect(() => {
    !function(b,e){
      (b[e] = b[e] || []).push({
        flipto: {
          bookingEngine: "Demo",
          companyCode: "XX",
          code: "YYYY",
        },
      })
    }(window,'fliptoDataLayer');
  }, []); // 空依赖数组确保仅执行一次

  return <div>页面内容</div>;
}

方案2:在全局文档中添加脚本(全局生效)

Pages Router(Next.js 12及以下)

修改pages/_document.js,通过dangerouslySetInnerHTML插入脚本:

import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
  render() {
    return (
      <Html>
        <Head>
          <script
            dangerouslySetInnerHTML={{
              __html: `
                !function(b,e){
                  (b[e] = b[e] || []).push({
                    flipto: {
                      bookingEngine: "Demo",
                      companyCode: "XX",
                      code: "YYYY",
                    },
                  })
                }(window,'fliptoDataLayer');
              `
            }}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;
App Router(Next.js 13+)

在app/layout.js中使用Next.js官方Script组件,自动处理客户端执行逻辑:

import { Script } from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html lang="zh-CN">
      <body>
        {children}
        <Script id="flipto-init-script">
          {`
            !function(b,e){
              (b[e] = b[e] || []).push({
                flipto: {
                  bookingEngine: "Demo",
                  companyCode: "XX",
                  code: "YYYY",
                },
              })
            }(window,'fliptoDataLayer');
          `}
        </Script>
      </body>
    </html>
  );
}

内容的提问来源于stack exchange,提问作者Agustin G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:01:10