admin管理员组文章数量:1397049
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.
本文标签: javascriptHow to keep fetch working when iOS minimizes the browserStack Overflow
版权声明:本文标题:javascript - How to keep fetch working when iOS minimizes the browser? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744148425a2592948.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论