如何检测嵌入网站的Trustpilot TrustBox组件是否为空数据
检测Trustpilot TrustBox空数据的实现方法
以下是两种可直接落地的检测方案:
方案1:基于官方暴露API检测
Trustpilot挂载的window.Trustpilot.Modules.WidgetManagement对象提供了getLoadedWidgets()方法,可获取所有已加载的TrustBox实例,通过实例携带的业务数据字段即可判断是否为空:
// 轮询等待Trustpilot对象加载完成 function checkTrustBoxData() { // 检测Trustpilot对象是否完成挂载 if (!window.Trustpilot?.Modules?.WidgetManagement) { setTimeout(checkTrustBoxData, 200); return; } // 获取所有已加载的TrustBox实例 const allWidgets = window.Trustpilot.Modules.WidgetManagement.getLoadedWidgets(); // 筛选空数据的组件 const emptyWidgets = allWidgets.filter(widget => { const data = widget.data; // 核心判定规则:无星级数据 或 有效评论数为0即为空数据 return !data?.stars || (data?.numberOfReviews ?? 0) === 0; }); if (emptyWidgets.length) { // 此处添加你的自定义逻辑,比如隐藏空组件、替换为占位内容等 console.log('检测到空数据TrustBox:', emptyWidgets); } } checkTrustBoxData();
方案2:DOM兜底检测方案
如果因为TrustBox版本差异导致API不生效,可直接通过渲染后的DOM特征判断,空数据的TrustBox会默认携带no-reviews类名,核心展示字段内容为空:
function checkTrustBoxByDom() { // 获取页面所有TrustBox节点 const allTrustBoxes = document.querySelectorAll('.trustpilot-widget'); allTrustBoxes.forEach(box => { const isEmpty = !!box.querySelector('.no-reviews') || !box.querySelector('.trustscore-rating')?.textContent?.trim() || (box.querySelector('.review-count')?.textContent?.trim() || '0') === '0'; if (isEmpty) { // 自定义逻辑示例:隐藏空数据组件 box.style.display = 'none'; } }) } // 页面资源全部加载完成后调用,确保TrustBox已渲染 window.addEventListener('load', checkTrustBoxByDom);
两种方案可以组合使用,优先调用官方API检测,兜底使用DOM判断,兼容不同版本的TrustBox组件。
内容的提问来源于stack exchange,提问作者Veewoo
相关产品推荐
相关产品推荐

