我正在开发的webapp是通过post在webview中打开的。帖子正文参数(上下文用户输入)被插入到index.html中。
因此,由于缺少上下文输入,因此重复加载失败。
官方文档说,对此无能为力。它说您现在所能做的就是首先进入网络并启用导航预加载。(https://developers.google.com/web/tools/workbox/modules/workbox-navigation-preload ---------“此功能旨在减少无法预缓存其开发人员的导航延迟HTML……”)
因此,我正在寻找一种在使用前编辑缓存的index.html的方法。我想将post正文参数插入到index.html中。我找不到有关编辑缓存的任何文档。因此,来自社区的任何帮助/投入将不胜感激。
工作箱!==服务工作者。Workbox是建立在服务人员之上的,但是原始服务人员可以让您完全控制请求和响应,因此您几乎可以做任何事情。
您可以通过以下方式更改回复文字:
addEventListener('fetch', event => {
event.respondWith(async function() {
// Get a cached response:
const cachedResponse = await caches.match('/');
// Get the text of the response:
const responseText = await cachedResponse.text();
// Change it:
const newText = responseText.replace(/Hello/g, 'Goodbye');
// Serve it:
return new Response(newText, cachedResponse);
}());
});
这里存在一个潜在的性能问题,您最终将整个响应加载到内存中,并在提供第一个字节之前进行替换工作。稍加努力,您就可以以流方式进行替换:
function streamingReplace(find, replace) {
let buffer = '';
return new TransformStream({
transform(chunk, controller) {
buffer += chunk;
let outChunk = '';
while (true) {
const index = buffer.indexOf(find);
if (index === -1) break;
outChunk += buffer.slice(0, index) + replace;
buffer = buffer.slice(index + find.length);
}
outChunk += buffer.slice(0, -(find.length - 1));
buffer = buffer.slice(-(find.length - 1));
controller.enqueue(outChunk);
},
flush(controller) {
if (buffer) controller.enqueue(buffer);
}
})
}
addEventListener('fetch', event => {
const url = new URL(event.request.url);
if (!(url.origin === location.origin && url.pathname === '/sw-content-change/')) return;
event.respondWith((async function() {
const response = await fetch(event.request);
const bodyStream = response.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(streamingReplace('Hello', 'Goodbye'))
.pipeThrough(new TextEncoderStream());
return new Response(bodyStream, response);
})());
});
您需要的另一部分是获取响应的POST正文:
addEventListener('fetch', event => {
event.respondWith(async function() {
if (event.request.method !== 'POST') return;
const formData = await event.request.formData();
// Do whatever you want with the form data…
console.log(formData.get('foo'));
}());
});
有关API,请参见MDN页面FormData
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句