现代风
使用 Web Share Target API
首先,在 Web 应用清单中声明一个 share_target
,其中列出了 action
(处理共享文件的网址)、method
("POST"
用于文件)和 enctype
("multipart/form-data"
用于文件)以及 params
对象,其中包含一个 files
属性,该属性具有一个带有 name
和 accept
属性的对象数组,其中列出了可共享的文件类型以及用于获取它们的名称。
{
"share_target": {
"action": "/receive-files/",
"method": "POST",
"enctype": "multipart/form-data",
"params": {
"files": [
{
"name": "image",
"accept": ["image/jpeg", "image/png", "image/webp", "image/gif"]
}
]
}
}
}
然后,您需要在 Service Worker 中处理传入的 POST
请求。该文件暂时存储在媒体缓存中,以便在客户端中使用。这可以通过使用特殊标记查询参数(如 share-target
)将应用重定向到网址来实现。
self.addEventListener('fetch', (fetchEvent) => {
if (fetchEvent.request.url.endsWith('/receive-files/') && fetchEvent.request.method === 'POST') {
return fetchEvent.respondWith(
(async () => {
const formData = await fetchEvent.request.formData();
const image = formData.get('image');
const keys = await caches.keys();
const mediaCache = await caches.open(keys.filter((key) => key.startsWith('media'))[0]);
await mediaCache.put('shared-image', new Response(image));
return Response.redirect('./?share-target', 303);
})(),
);
}
});
最后,您需要在客户端中使用该文件。
window.addEventListener('load', async () => {
if (location.search.includes('share-target')) {
const keys = await caches.keys();
const mediaCache = await caches.open(
keys.filter((key) => key.startsWith('media'))[0],
);
const image = await mediaCache.match('shared-image');
if (image) {
const blob = await image.blob();
await mediaCache.delete('shared-image');
// Handle the shared file somehow.
}
}
});
深入阅读
演示
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="manifest" href="manifest.json" />
<title>How to receive shared files</title>
<link rel="stylesheet" href="style.css" />
<!-- TODO: Devsite - Removed inline handlers -->
<!-- <script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', async () => {
const registration = await navigator.serviceWorker.register(
'sw.js',
);
console.log(
'Service worker registered for scope',
registration.scope,
);
});
}
</script>
<script src="script.js" type="module"></script> -->
</head>
<body>
<h1>How to receive shared files</h1>
<p>Install the app. After the installation, try sharing an image to it from another app.
</body>
</html>
CSS
html {
box-sizing: border-box;
font-family: system-ui, sans-serif;
color-scheme: dark light;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
margin: 1rem;
}
img {
height: auto;
max-width: 100%;
display: block;
}
JS
window.addEventListener('load', async () => {
if (location.search.includes('share-target')) {
const keys = await caches.keys();
const mediaCache = await caches.open(
keys.filter((key) => key.startsWith('media'))[0],
);
const image = await mediaCache.match('shared-image');
if (image) {
const blob = await image.blob();
await mediaCache.delete('shared-image');
// Handle the shared file somehow.
}
}
});