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

从Android应用返回后自动刷新浏览器页面的技术实现咨询

解决方案:移动端浏览器返回后自动刷新页面推进问卷流程

针对你用Django搭建的分步问卷平台,需要在用户从Unity Android游戏返回浏览器时自动刷新页面推进流程,这里提供几个实用方案:

方案1:利用浏览器页面可见性事件(最通用)

浏览器原生提供visibilitychange事件,可监听页面从隐藏到可见的状态变化——正好匹配用户从游戏切回浏览器的动作。结合Django传递的当前步骤标识,就能精准触发刷新逻辑。

前端实现(嵌入步骤2的页面)

// 监听页面可见性变化
document.addEventListener('visibilitychange', function() {
    // 仅当页面从隐藏变为可见时执行逻辑
    if (!document.hidden) {
        // 从Django渲染的页面中获取当前步骤标识
        const currentStep = document.body.dataset.currentStep;
        // 确认是等待游戏结束的步骤,才执行刷新/跳转
        if (currentStep === 'waiting_for_game') {
            // 整页刷新,Django后端会根据用户状态返回步骤3的页面
            window.location.reload();
            
            // 可选:如果不想整页刷新,用异步请求更新状态后跳转
            // fetch('/api/update-game-status/', {
            //     method: 'POST',
            //     credentials: 'same-origin',
            //     headers: {'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value}
            // })
            // .then(res => res.json())
            // .then(data => {
            //     if (data.success) window.location.href = data.next_url;
            // });
        }
    }
});

Django后端配合

渲染步骤2的页面时,在<body>标签中添加步骤标识:

<body data-current-step="waiting_for_game">
    <!-- 页面内容:引导用户打开游戏的按钮/Intent链接 -->
</body>

方案2:Unity+后端状态同步(更高准确性)

如果担心visibilitychange误触发(比如用户切到其他APP而非游戏),可以让Unity游戏在结束时主动通知Django后端更新用户状态,前端通过轮询监听状态变化,自动推进流程。

Unity端实现(C#)

游戏结束时调用后端接口标记任务完成,再退出应用:

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class GameCompletionHandler : MonoBehaviour
{
    // 替换为你的Django后端接口地址
    private const string UpdateStatusUrl = "https://your-domain.com/api/mark-game-done/";

    public void OnGameFinished()
    {
        // 从PlayerPrefs或Intent参数中获取当前用户ID
        string userId = PlayerPrefs.GetString("current_user_id");
        StartCoroutine(SendCompletionRequest(userId));
    }

    IEnumerator SendCompletionRequest(string userId)
    {
        WWWForm form = new WWWForm();
        form.AddField("user_id", userId);

        using (UnityWebRequest request = UnityWebRequest.Post(UpdateStatusUrl, form))
        {
            yield return request.SendWebRequest();

            if (request.result == UnityWebRequest.Result.Success)
            {
                Debug.Log("状态更新成功");
                Application.Quit(); // 退出游戏返回浏览器
            }
            else
            {
                Debug.LogError("状态更新失败:" + request.error);
                // 可选:弹出提示,让用户手动返回浏览器刷新
            }
        }
    }
}

Django后端接口

from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.shortcuts import reverse

@login_required
def mark_game_done(request):
    if request.method == "POST":
        # 更新当前用户的游戏完成状态
        request.user.profile.game_completed = True
        request.user.profile.save()
        return JsonResponse({"success": True})
    return JsonResponse({"success": False})

@login_required
def check_game_status(request):
    # 返回当前用户的游戏状态及下一步URL
    return JsonResponse({
        "is_completed": request.user.profile.game_completed,
        "next_step_url": reverse("questionnaire_step3")
    })

前端轮询监听

let statusCheckInterval;

// 启动轮询
function startStatusCheck() {
    statusCheckInterval = setInterval(() => {
        fetch('/api/check-game-status/', { credentials: 'same-origin' })
        .then(res => res.json())
        .then(data => {
            if (data.is_completed) {
                clearInterval(statusCheckInterval);
                window.location.href = data.next_step_url;
            }
        });
    }, 3000); // 每3秒检查一次
}

// 页面加载时启动轮询
window.addEventListener('load', startStatusCheck);

// 页面隐藏时暂停轮询,节省资源
document.addEventListener('visibilitychange', () => {
    if (document.hidden) {
        clearInterval(statusCheckInterval);
    } else {
        startStatusCheck();
    }
});

方案3:Android Intent返回数据(局限性大)

部分自定义浏览器支持接收Intent返回的结果,但主流移动端浏览器(如Chrome、Safari)不支持此功能,因此仅作为备选:

  • Unity游戏退出时通过Android的setResult()返回完成标识
  • 浏览器需自定义Intent协议处理返回数据,触发页面刷新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:32:49