问题描述
我可以将我的Progressive Web App注册为共享图片目标(Chrome Android 76支持 ):
I can register my Progressive Web App as a share target for images (supported from Chrome Android 76):
"share_target": {
"action": "/share-target",
"method": "POST",
"enctype": "multipart/form-data",
"params": {
"files": [
{
"name": "myImage",
"accept": ["image/jpeg", "image/png"]
}
]
}
}
然后我可以拦截尝试在服务工作者中与应用共享图像的尝试:
I can then intercept attempts to share images to the app in a service worker:
self.addEventListener('fetch', e => {
if (e.request.method === 'POST' && e.request.url.endsWith('/share-target')) {
// todo
}
})
如何在离线PWA中显示共享图像?
How would I display the shared image in my offline PWA?
推荐答案
这里有一些不同的步骤.
There are a few different steps to take here.
我在 https://web-share-offline.glitch.me/上汇总了一个工作示例.,其来源为 https://glitch.com/edit/#!/web-share-offline
这是先决条件,我通过生成将使用工作箱.
This is a prerequisite, and I accomplished it by generating a service worker that would precache my HTML, JS, and CSS using Workbox.
加载首页时运行的JS使用Cache Storage API读取已缓存的图像URL的列表,以在与每个URL对应的页面上创建< img>
元素一个.
The JS that runs when the home page is loaded uses the Cache Storage API to read a list of image URLs that have been cached, to creates <img>
elements on the page corresponding to each one.
我也为此使用了Workbox,但这涉及更多.重点是:
I also used Workbox for this, but it's a bit more involved. The salient points are:
- 确保您拦截了针对配置的共享目标URL的
POST
请求. - 由您决定要读取共享图像的正文,然后使用Cache Storage API将它们写入本地缓存中.
- 将共享图像保存到缓存后,最好使用POST ="noreferrer">
HTTP 303
重定向响应,以便浏览器将显示Web应用程序的实际主页.
- Make sure that you intercept
POST
requests for the configured share target URL. - It's up to you to read in the body of the shared images and to write them to your local cache using the Cache Storage API.
- After you save the shared image to cache, it's a good idea to respond to the
POST
with aHTTP 303
redirected response, so that the browser will display the actual home page for your web app.
这是我用来处理此问题的Workbox配置代码:
Here's the Workbox configuration code that I used to handle this:
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',
},
}],
};
这篇关于如何在PWA共享目标中脱机处理图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!