【问题标题】:Get an element created by a script in react without ref在没有参考的情况下获取由脚本创建的元素
【发布时间】:2022-01-21 00:55:42
【问题描述】:

我有一个由脚本创建的聊天按钮(zendesk 聊天)。它会在页面中生成一个 ID 为“launcher”的 iframe。 我正在使用 Nextjs 并尝试获取此元素,但由于没有代码,因此无法附加参考。 我正在网上挖掘解决方案,我已经尝试过类似的方法(在页脚组件中,因为它在所有页面上,我能够弄清楚我在哪个页面上):

React.useLayoutEffect(() => {
    function checkElExist() {
      if (typeof document !== 'undefined') {
        const el = document.querySelector('#launcher');
        if (!isSingleVehiclePage) {
          console.log('NOT VEHICLE', el);
          if (el) {
            el.classList.remove('inVehicle');
            el.classList.add('notInVehiclePage');
          }
        } else {
          console.log('IN VEHICLE', el);
          if (el) {
            el.classList.remove('notInVehiclePage');
            el.classList.add('inVehicle');
          }
        }
      }
    }
    window.addEventListener('load', checkElExist);
    return () => window.removeEventListener('load', checkElExist);
  }, [isSingleVehiclePage]);

我不知道是否是正确的解决方案。它有点工作,但有时该元素为空,特别是当我从外部链接进入该特定页面时(而不是在我浏览网站时)。 有没有可能得到这个元素?我的目标是根据特定页面添加/删除一个类。

谢谢

编辑:我不知道它是否相关,但在 html 中,iframe 不在我的“__next”div 中。在下图中,我圈出了 __next div、footer div(执行我的 useLayoutEffect 代码的地方)和我想要获取的 iframe。

【问题讨论】:

    标签: javascript reactjs next.js ref


    【解决方案1】:

    已解决: 我使用一个每 1000 毫秒递归运行一次的函数。如果在 9000 毫秒内找不到元素,则停止。

    React.useEffect(() => {
        waitForElementToDisplay(
          '#launcher',
          function (el: any) {
            checkElExist(el);
          },
          1000,
          9000
        );
        function checkElExist(el: any) {
          if (!isSingleVehiclePage) {
            console.log('NOT VEHICLE', el);
            el.classList.remove('inVehicle');
            el.classList.add('notInVehiclePage');
          } else {
            console.log('IN VEHICLE', el);
            el.classList.remove('notInVehiclePage');
            el.classList.add('inVehicle');
          }
        }
      }, [isSingleVehiclePage]);
    
    function waitForElementToDisplay(
        selector: string,
        callback: any,
        checkFrequencyInMs: number,
        timeoutInMs: number
      ) {
        const startTimeInMs = Date.now();
        (function loopSearch() {
          if (document && document.querySelector(selector) != null) {
            console.log('found');
            const element = document.querySelector(selector);
            callback(element);
            return;
          } else {
            setTimeout(function () {
              if (timeoutInMs && Date.now() - startTimeInMs > timeoutInMs) return;
              loopSearch();
            }, checkFrequencyInMs);
          }
        })();
      }
    

    【讨论】:

      猜你喜欢
      • 2016-07-24
      • 1970-01-01
      • 2020-11-23
      • 2011-03-28
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-21
      相关资源
      最近更新 更多