You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移动端页面刷新检测失效求助:PC端正常移动端异常

问题排查与修复方案

你的代码在PC端正常但移动端失效,大概率是以下几个原因导致的,对应修复方案如下:

1. 移动端隐私模式限制sessionStorage

多数移动端浏览器(比如Safari隐私模式)会禁用sessionStorage,直接调用setItem会抛出异常,阻断后续代码执行。

修复方案:
用try-catch包裹sessionStorage操作,同时增加localStorage降级方案(需通过时间戳判断会话有效期,避免持久化干扰):

window.addEventListener('load', function() {
    let isReloaded = false;
    // 处理sessionStorage可能的异常
    try {
        isReloaded = sessionStorage.getItem('isReloaded') === 'true';
        if (!isReloaded) {
            sessionStorage.setItem('isReloaded', 'true');
        }
    } catch (e) {
        // 隐私模式下用localStorage+时间戳判断会话
        const lastVisit = localStorage.getItem('lastVisit');
        const now = Date.now();
        // 30分钟内视为同一会话,超过则判定为首次加载
        if (!lastVisit || now - parseInt(lastVisit) > 30 * 60 * 1000) {
            isReloaded = false;
            localStorage.setItem('lastVisit', now.toString());
        } else {
            isReloaded = true;
        }
    }

    // 后续AJAX逻辑调整
    const isRefreshed = isReloaded ? 'true' : 'false';
    // 从cookie获取CSRF token,替代模板渲染
    function getCsrfToken() {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, 10) === 'csrftoken=') {
                    cookieValue = decodeURIComponent(cookie.substring(10));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrfToken = getCsrfToken();

    // 用原生fetch替代jQuery,避免依赖问题
    fetch(window.location.pathname, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRFToken': csrfToken
        },
        body: new URLSearchParams({
            'is_refreshed': isRefreshed,
            'csrfmiddlewaretoken': csrfToken
        })
    })
    .then(response => response.json())
    .then(data => console.log(data.message))
    .catch(error => console.error(error));
});

2. jQuery依赖加载失败

移动端网络环境或CDN屏蔽可能导致jQuery加载失败,使得$.ajax无法执行。

修复方案:

  • 在代码开头添加jQuery存在性校验:
if (typeof $ === 'undefined') {
    console.error('jQuery未加载');
    return;
}
  • 或者直接改用上述代码中的原生fetch,完全移除jQuery依赖。

3. load事件触发时机延迟

移动端页面的load事件需等待所有资源(图片、样式等)加载完成,可能因资源加载缓慢导致事件触发过晚,甚至在某些场景下不触发。

修复方案:
替换为DOMContentLoaded事件,它会在DOM结构加载完成后立即执行,无需等待资源加载:

window.addEventListener('DOMContentLoaded', function() {
    // 原逻辑代码...
});

4. AJAX请求URL为空的歧义

url: ''在部分移动端浏览器中可能解析为无效路径,导致请求失败。

修复方案:
明确指定请求URL为当前页面路径:

url: window.location.pathname,

内容的提问来源于stack exchange,提问作者iulian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 11:30:28