这里有几个不同的步骤。
我在https://web-share-offline.glitch.me/上整理了一个工作示例,源代码在https://glitch.com/edit/#!/web-share-offline
确保您的网络应用可以离线运行
这是一个先决条件,我通过生成一个使用Workbox预缓存我的 HTML、JS 和 CSS 的 service worker 来完成它。
加载主页时运行的 JS 使用 Cache Storage API 读取已缓存的图像 URL 列表,<img>在页面上创建对应的元素。
创建将缓存图像的共享目标处理程序
我也为此使用了 Workbox,但它涉及的更多。重点是:
- 确保拦截
POST对配置的共享目标 URL 的请求。
- 您可以读取共享图像的正文并使用缓存存储 API 将它们写入本地缓存。
- 将共享图像保存到缓存后,最好
POST使用HTTP 303重定向的响应来响应,以便浏览器显示您的 Web 应用程序的实际主页。
这是我用来处理此问题的 Workbox 配置代码:
const shareTargetHandler = async ({event}) => {
const formData = await event.request.formData();
const cache = await caches.open('images');
await cache.put(
// TODO: Come up with a more meaningful cache key.
`/images/${Date.now()}`,
// TODO: Get more meaningful metadata and use it
// to construct the response.
new Response(formData.get('image'))
);
// After the POST succeeds, redirect to the main page.
return Response.redirect('/', 303);
};
module.exports = {
// ... other Workbox config ...
runtimeCaching: [{
// Create a 'fake' route to handle the incoming POST.
urlPattern: '/share-target',
method: 'POST',
handler: shareTargetHandler,
}, {
// Create a route to serve the cached images.
urlPattern: new RegExp('/images/\\d+'),
handler: 'CacheOnly',
options: {
cacheName: 'images',
},
}],
};