javascript - How to keep fetch working when iOS minimizes the browser? - Stack Overflow

I'm working on a web application using Laravel, Nginx on the server, Express for the "API&quo

I'm working on a web application using Laravel, Nginx on the server, Express for the "API" and I'm facing an issue with session management when users switch tabs or minimize the browser. (At least on iOS, is the only device I tested yet.)

The problem is that when a user leaves the tab (I tested on Chrome & Safari), the fetch seems to break or doesn't stay active properly. I want the user to be able to leave the tab momentarily (that's necessary because need to accept on another app), but when they return, the session should still be active and the state should not be lost. Which isn't happening and isn't passing on desktop.

The goal is to keep the session intact when the user is inactive for a while and allow them to continue where they left off when they return to the browser.

Has anyone experienced something similar? What would be the best way to handle this?

I let here some of my actual code:

The fetch from the view:

try {
    const response = await fetch('', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ data1, data2})
    });

    if (!response.body) {
        throw new Error("Empty response");
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let receivedText = "";

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value, { stream: true });
        receivedText += chunk;

        const dataJSON = JSON.parse(chunk);
        if (dataJSON.success && dataJSON.verificationCode) {
            verificationDiv.innerText = `Verification code: ${dataJSON.verificationCode}`;
        } else {
            verificationDiv.innerText = 'Error to get code.';
        }
    }

    const jsonParts = receivedText.split('\n').map(part => part.trim()).filter(part => part.length > 0);

    if (jsonParts.length === 0) {
        throw new Error("Didn't get the JSON data");
    }

    const lastJson = jsonParts[jsonParts.length - 1];

    let dataFromResponse;
    try {
        dataFromResponse = JSON.parse(lastJson);
    } catch (error) {
        console.error("Error parsing JSON:", error);
        alert("Error.");
        return;
    }

    const data = dataFromResponse.data;

    const name = data.name;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;

    function centsConvert(valor) {
        const convertValue = valor.replace('.', '').replace(',', '.');
        return Math.round(parseFloat(convertValue) * 100);
    }

    registrationData = {
        name: data.name,
        full_name: data.name,
        email: document.getElementById('email').value,
        telefono: document.getElementById('telefono').value,
        password: document.getElementById('password').value,
        dni: data.dni,
    };

    step2Container.style.display = 'block';
    let divVerification = document.getElementById('verificationCode');
    divVerification.innerText = '';
    let containerSpinner = document.getElementById('spinner-container');
    containerSpinner.style.display = 'none';
} finally {
    spinnerContainer.style.display = 'none';
    btn.disabled = false;
}

The API:

app.post('/puppeteer/webscrape', async (req, res) => {
  const { dni, fecha } = req.body;

  const dniRegex = /^\d{8}[A-Za-z]$/;
  const fechaRegex = /^\d{4}\-\d{2}\-\d{2}$/;

  if (!dniRegex.test(dni)) {
    return res.status(400).json({ error: 'Invalid DNI.' });
  }

  if (!fechaRegex.test(fecha)) {
    return res.status(400).json({ error: 'Invalid date.' });
  }

  try {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Transfer-Encoding', 'chunked');
    res.write(JSON.stringify({ success: true, message: 'Started process.' }) + '\n');
    res.flushHeaders(); 

    setImmediate(async () => {
      try {
        const { success, verificationCode, error } = await initializeBrowser(dni, fecha);
        if (!success) {
          logError(`Error en la inicialización: ${error}`);
          return;
        }

        const name = await handleRedirectionAndClick(dni);
        if (name) {
          console.log('Finished:', apellidosYNombres);
        } else {
          logError('Error');
        }
      } catch (err) {
        logError(`Error: ${err}`);
      }
    });

  } catch (error) {
    console.log(error);
    logError(`Error: ${error}`);
    res.write(JSON.stringify({ error: 'Error.' }));
    res.end();
  }
});

This only happens on mobile, in desktop works perfectly.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744148425a4560534.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信