简体   繁体   English

Gatsby 3rd 方脚本未按预期工作

[英]Gatsby 3rd party scripts not working as intended

I have the problem with including fastspring to my gatsby project.我在我的 gatsby 项目中包含 fastspring 时遇到了问题。 Problem is the following: I add the script in html head but it doesn't work on all pages(it works only if I refresh the page) I tried to fix that by inserting script in html.js, with gatsby-ssr.js and gatsby-browser.js问题如下:我在 html 头中添加了脚本,但它不适用于所有页面(它仅在我刷新页面时才有效)我试图通过在 html.js 中插入脚本来解决这个问题,使用 gatsby-ssr.js和 gatsby-browser.js

gatsby-browser.js盖茨比浏览器.js 在此处输入图像描述

I put the same code in gatsby-ssr.js, I have also tried with Helmet but nothing works for me I want it to work on all the pages without needing to refresh the page, so if somebody could help me with this.我将相同的代码放在 gatsby-ssr.js 中,我也尝试过使用 Helmet,但对我没有任何作用我希望它可以在所有页面上工作而无需刷新页面,所以如果有人可以帮助我解决这个问题。 Thanks in advance: :)提前致谢: :)

Seems like an old issue, but someone might still have the problem.似乎是一个老问题,但有人可能仍然有问题。 I did search for a solution to it for some time and in the end, I went with the following.我确实寻找了一段时间的解决方案,最后,我选择了以下方法。

  1. I created a component called FastSpringStoreApi.js.我创建了一个名为 FastSpringStoreApi.js 的组件。 It loads FastSpring API and subscribes to 2 callback events from it - data-popup-closed and data-data-callback .它加载 FastSpring API 并从中订阅 2 个回调事件 - data-popup-closeddata-data-callback I used this two to dispatch custom js events for which I listen in my FastSpring provider.我使用这两个来调度我在我的 FastSpring 提供程序中侦听的自定义 js 事件。 These 2 events contain all information needed for store to function (items, pricing, cart information)这 2 个事件包含存储到 function 所需的所有信息(项目、定价、购物车信息)

Note: there is a reason I save data into sessionStorage.注意:我将数据保存到 sessionStorage 是有原因的。 The event can be dispatched before React hydrates.该事件可以在 React 水合物之前被调度。 And in cases like this I take data in session storage as initial state in my reducers.在这种情况下,我将 session 存储中的数据作为我的减速器中的初始 state 。

import React from 'react';
import {
  FS_EVENTS,
  FS_SESSION_KEY
} from './FastSpringStore.keys';

export default ({ storeFrontId }) => (
  <>
    <script
      type="text/javascript"
      dangerouslySetInnerHTML= {{
        __html:`
          function raiseFSPopupCloseEvent(data) {
            var popupCloseEvent = new CustomEvent(
             '${FS_EVENTS.POPUP_CLOSE}',
             { detail: data }
            );
            window.dispatchEvent(popupCloseEvent);
          }
          
          function raiseFSDataUpdateEvent(data) {
            var dataUpdateEvent = new CustomEvent(
             '${FS_EVENTS.DATA_UPDATE}',
             { detail: data }
            );
            
            window
              .sessionStorage
              .setItem(
                '${FS_SESSION_KEY}',
                 JSON.stringify(data)
               )
              
            window.dispatchEvent(dataUpdateEvent);
          }
        `
      }}
    />
    <script
      id="fsc-api"
      src="https://d1f8f9xcsvx3ha.cloudfront.net/sbl/0.8.5/fastspring-builder.min.js"
      type="text/javascript"
      data-popup-closed="raiseFSPopupCloseEvent"
      data-data-callback="raiseFSDataUpdateEvent"
      data-continuous="true"
      data-storefront={storeFrontId}
    />
  </>
)
  1. I load this component inside gatsby-ssr.js only我只在gatsby-ssr.js加载这个组件
export const onRenderBody = ({ setHeadComponents }) => {
  setHeadComponents([
    <FastSpringStoreApi
      key="fast-spring-store-api"
      storeFrontId="..."
    />,
  ])
}
  1. I have FasSpringStore provider where I subscribe to my fs events.我有订阅我的 fs 事件的 FasSpringStore 提供程序。 Looks like this.看起来像这样。 With it I can get all data needed further down to any of the components.有了它,我可以将所需的所有数据进一步深入到任何组件。
useEffect(() => {
    const onPopupClosed = (data) => {
      // Popup was closed and order was finished (we have order id)
      if (_has(data.detail, 'id')) {
        // Navigate to home page
        // TODO: Show thank you page in the future
        navigate('/')
        dispatch(cleanShopStore())
      }
    }

    const onDataUpdate = (data) => {
      dispatch(
        setOrderInfo(
          mapFSDataToPayload(
            data.detail
          )
        )
      )
    }

    window.addEventListener(FS_EVENTS.POPUP_CLOSE, onPopupClosed, false);
    window.addEventListener(FS_EVENTS.DATA_UPDATE, onDataUpdate, false);


    return () => {
      window.removeEventListener(FS_EVENTS.POPUP_CLOSE, onPopupClosed)
      window.removeEventListener(FS_EVENTS.DATA_UPDATE, onDataUpdate)
      window.sessionStorage.removeItem(FS_SESSION_KEY)
    }
  }, [])
  1. Inside gatsby-ssr.js I wrap my root element with store providergatsby-ssr.js ,我将根元素与 store provider 一起包装
export const wrapRootElement = ({ element }) => (
  <FastSpringStoreProvider>
    {element}
  </FastSpringStoreProvider>
);
  1. Same goes for gatsby-browser.js gatsby-browser.js也是如此
export const wrapRootElement = ({ element }) => (
  <FastSpringStoreProvider>
    {element}
  </FastSpringStoreProvider>
);

Hope this gives some ideas for FastSpring implementation.希望这可以为 FastSpring 的实现提供一些想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM