React中如何无论是否启用广告拦截器都正常调用API并展示资料弹窗
问题核心原因
原来的逻辑有两个限制导致需求无法实现:
checkInAPI被包裹在if (!detected)的判断里,只有没检测到广告拦截时才会调用- 个人资料弹窗的显示逻辑额外加了
!adBlock的限制,只要检测到广告拦截就不会展示,即使用户手动关闭了广告拦截提示窗也不生效
具体修改步骤
1. 调整Main.js的API调用逻辑
去掉API调用的广告拦截判断,无论是否检测到广告拦截都调用checkInAPI,同时把广告拦截的检测结果存储下来供全局使用:
// Main.js componentDidMount() { // 检测广告拦截,结果存在localStorage供其他组件调用 detectAnyAdblocker().then((detected) => { localStorage.setItem('adBlockDetected', detected); }); // 无论是否有广告拦截都直接调用checkInAPI this.props.checkInAPI(params).then((resp) => { localStorage.setItem('firstTimeUserVisit', resp && resp.data === true); const userId = localStorage.getItem('userId'); }); } render() { return ( <AdBlock /> ) }
2. 调整AdBlock.js的状态逻辑
把关闭广告拦截提示的状态也存到localStorage,方便其他组件读取,同时移除全局变量closeAdBlock避免状态污染:
// AdBlock.js const AdBlock = ({ eventData }) => { const [adBlock, setAdBlock] = useState(false); const onCloseAdBlock = () => { setAdBlock(false); localStorage.setItem('adBlockPromptClosed', 'true'); }; useEffect(() => { const promptClosed = localStorage.getItem('adBlockPromptClosed') === 'true'; if (!promptClosed) { detectAnyAdblocker().then((detected) => { if (detected) { setAdBlock(true); } }); } }, []); return ( <PopupModal id="adblock-popup" custClassName={'adblock-popups'} onCloseFunc={() => onCloseAdBlock()} showModal={adBlock} > ..... </PopupModal> ) }
3. 调整Profile.js的弹窗显示逻辑
移除原来的!adBlock限制,改为判断“是首次访问 且(没检测到广告拦截 或 广告拦截提示窗已经被用户关闭)”:
// Profile.js const [showProfilePopup, setShowProfilePopup] = useState(false); const firstTimeCheckIn = localStorage.getItem('firstTimeUserVisit') === 'true'; const adBlockDetected = localStorage.getItem('adBlockDetected') === 'true'; const adBlockPromptClosed = localStorage.getItem('adBlockPromptClosed') === 'true'; useEffect(() => { if (firstTimeCheckIn && (!adBlockDetected || adBlockPromptClosed)) { setShowProfilePopup(true); } }, [firstTimeCheckIn, adBlockDetected, adBlockPromptClosed]); return ( {showProfilePopup && (<PopupModal> ..... </PopupModal>)} )
效果说明
修改后完全匹配需求:
- 无论用户是否开启广告拦截,页面加载时都会直接调用
checkInAPI,首次访问的标记会正常存储 - 如果用户没开广告拦截,首次访问直接显示个人资料弹窗
- 如果用户开了广告拦截,先显示广告拦截提示,用户手动关闭提示后,个人资料弹窗会自动弹出
内容的提问来源于stack exchange,提问作者Anurag Sharma
相关产品推荐
相关产品推荐

