【发布时间】: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