use*_*436 6 javascript offline service-worker progressive-web-apps
我们有一个Web应用程序(使用AngularJS构建),我们也逐渐添加PWA'功能'(服务工作者,可启动,通知等).我们的网络应用程序具有的功能之一是能够在离线时完成Web表单.目前,我们在离线时将数据存储在IndexedDB中,并且只需鼓励用户将数据一旦上线就将其推送到服务器("此表单已保存到您的设备中.现在您已重新上线,您应该保存它到云端......").我们会在某些时候自动执行此操作,但目前不需要这样做.
我们正在为这些Web表单添加一个功能,用户可以将文件(图像,文档)附加到表单,也许在整个表单的几个点上.
我的问题是 - 服务工作者有办法处理文件上传吗?以某种方式 - 也许 - 在离线时存储要上载的文件的路径,并在连接恢复后推送该文件?这是否适用于移动设备,我们是否可以访问这些设备上的"路径"?任何帮助,建议或参考将不胜感激.
当用户通过<input type="file">元素选择文件时,我们可以通过获得选择的文件fileInput.files。这给了我们一个FileList对象,其中的每一项都是File代表所选文件的对象。FileList并且File受到HTML5的结构化克隆算法的支持。
将项目添加到IndexedDB存储时,它将创建要存储的值的结构化克隆。由于结构化克隆算法支持FileList和File对象,因此这意味着我们可以将这些对象直接存储在IndexedDB中。
要在用户再次联机后执行这些文件上载,可以使用服务人员的后台同步功能。这是一篇介绍性文章有关如何执行。还有很多其他资源。
为了在后台同步代码运行后能够在请求中包含文件附件,您可以使用FormData。FormData允许将File对象添加到将发送到后端的请求中,并且可以在服务工作者上下文中使用。
Cache API 旨在存储请求(作为键)和响应(作为值),以便为网页缓存来自服务器的内容。在这里,我们讨论的是缓存用户输入以供将来分发到服务器。换句话说,我们并不是尝试实现缓存,而是实现消息代理,而这目前不是 Service Worker 规范(来源)处理的内容。
您可以通过尝试以下代码来弄清楚:
HTML:
<button id="get">GET</button>
<button id="post">POST</button>
<button id="put">PUT</button>
<button id="patch">PATCH</button>
Run Code Online (Sandbox Code Playgroud)
JavaScript:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js', { scope: '/' }).then(function (reg) {
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch(function (error) {
console.log('Registration failed with ' + error);
});
};
document.getElementById('get').addEventListener('click', async function () {
console.log('Response: ', await fetch('50x.html'));
});
document.getElementById('post').addEventListener('click', async function () {
console.log('Response: ', await fetch('50x.html', { method: 'POST' }));
});
document.getElementById('put').addEventListener('click', async function () {
console.log('Response: ', await fetch('50x.html', { method: 'PUT' }));
});
document.getElementById('patch').addEventListener('click', async function () {
console.log('Response: ', await fetch('50x.html', { method: 'PATCH' }));
});
Run Code Online (Sandbox Code Playgroud)
服务人员:
self.addEventListener('fetch', function (event) {
var response;
event.respondWith(fetch(event.request).then(function (r) {
response = r;
caches.open('v1').then(function (cache) {
cache.put(event.request, response);
}).catch(e => console.error(e));
return response.clone();
}));
});
Run Code Online (Sandbox Code Playgroud)
哪个抛出:
类型错误:不支持请求方法“POST”
类型错误:不支持请求方法“PUT”
类型错误:不支持请求方法“PATCH”
由于无法使用 Cache API,并且遵循Google 指南,IndexedDB 是作为持续请求的数据存储的最佳解决方案。然后,消息代理的实现是开发人员的责任,并且没有唯一的通用实现可以覆盖所有用例。有许多参数将决定解决方案:
window.navigator.onLine?有一定的超时时间吗?其他?self.addEventListener('online', ...)?navigator.connection?对于单个 StackOverflow 答案来说,这确实非常广泛。
话虽这么说,这是一个最小的工作解决方案:
HTML:
<input id="file" type="file">
<button id="sync">SYNC</button>
<button id="get">GET</button>
Run Code Online (Sandbox Code Playgroud)
JavaScript:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js', { scope: '/' }).then(function (reg) {
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch(function (error) {
console.log('Registration failed with ' + error);
});
};
document.getElementById('get').addEventListener('click', function () {
fetch('api');
});
document.getElementById('file').addEventListener('change', function () {
fetch('api', { method: 'PUT', body: document.getElementById('file').files[0] });
});
document.getElementById('sync').addEventListener('click', function () {
navigator.serviceWorker.controller.postMessage('sync');
});
Run Code Online (Sandbox Code Playgroud)
服务人员:
self.importScripts('https://unpkg.com/idb@5.0.1/build/iife/index-min.js');
const { openDB, deleteDB, wrap, unwrap } = idb;
const dbPromise = openDB('put-store', 1, {
upgrade(db) {
db.createObjectStore('put');
},
});
const idbKeyval = {
async get(key) {
return (await dbPromise).get('put', key);
},
async set(key, val) {
return (await dbPromise).put('put', val, key);
},
async delete(key) {
return (await dbPromise).delete('put', key);
},
async clear() {
return (await dbPromise).clear('put');
},
async keys() {
return (await dbPromise).getAllKeys('put');
},
};
self.addEventListener('fetch', function (event) {
if (event.request.method === 'PUT') {
let body;
event.respondWith(event.request.blob().then(file => {
// Retrieve the body then clone the request, to avoid "body already used" errors
body = file;
return fetch(new Request(event.request.url, { method: event.request.method, body }));
}).then(response => handleResult(response, event, body)).catch(() => handleResult(null, event, body)));
} else if (event.request.method === 'GET') {
event.respondWith(fetch(event.request).then(response => {
return response.ok ? response : caches.match(event.request);
}).catch(() => caches.match(event.request)));
}
});
async function handleResult(response, event, body) {
const getRequest = new Request(event.request.url, { method: 'GET' });
const cache = await caches.open('v1');
await idbKeyval.set(event.request.method + '.' + event.request.url, { url: event.request.url, method: event.request.method, body });
const returnResponse = response && response.ok ? response : new Response(body);
cache.put(getRequest, returnResponse.clone());
return returnResponse;
}
// Function to call when the network is supposed to be available
async function sync() {
const keys = await idbKeyval.keys();
for (const key of keys) {
try {
const { url, method, body } = await idbKeyval.get(key);
const response = await fetch(url, { method, body });
if (response && response.ok)
await idbKeyval.delete(key);
}
catch (e) {
console.warn(`An error occurred while trying to sync the request: ${key}`, e);
}
}
}
self.addEventListener('message', sync);
Run Code Online (Sandbox Code Playgroud)
关于该解决方案的一些说明:它允许缓存 PUT 请求以供将来的 GET 请求,并且还将 PUT 请求存储到 IndexedDB 数据库中以供将来同步。关于关键,我受到 Angular 的TransferHttpCacheInterceptor 的启发,它允许在服务器端呈现的页面上序列化后端请求,以供浏览器呈现的页面使用。它用作<verb>.<url>密钥。假设一个请求将覆盖另一个具有相同动词和 URL 的请求。
该解决方案还假设后端不返回204 No content作为 PUT 请求的响应,而是200返回正文中的实体。
处理文件上传/删除和几乎所有内容的一种方法是跟踪离线请求期间所做的所有更改。我们可以创建一个sync包含两个数组的对象,一个用于需要上传的待处理文件,另一个用于在我们重新上线时需要删除的已删除文件。
处理 service workerfetch事件,如果获取失败,那么我们必须处理文件列表的请求、上传文件到服务器的请求和从服务器删除文件的请求。如果我们没有这些请求中的任何一个,那么我们会从默认缓存中返回一个匹配项。
GET/uploads)和sync对象。我们concat将默认列表文件与文件一起pending删除,deleted然后我们返回带有 JSON 结果的新响应对象,因为服务器会返回它。PUTsync pending文件。如果文件不存在,那么我们为该文件创建一个新的缓存条目,我们使用 mime 类型和blobfrom 请求来创建一个新Response对象,它将被保存到默认缓存中。DELETEpending数组中删除该条目,否则如果它不在deleted数组中,则我们添加它。我们在最后更新列表、文件和同步对象缓存。(请阅读内嵌评论)
const cacheName = 'pwasndbx';
const syncCacheName = 'pwasndbx-sync';
const pendingName = '__pending';
const syncName = '__sync';
const filesToCache = [
'/',
'/uploads',
'/styles.css',
'/main.js',
'/utils.js',
'/favicon.ico',
'/manifest.json',
];
/* Start the service worker and cache all of the app's content */
self.addEventListener('install', function(e) {
console.log('SW:install');
e.waitUntil(Promise.all([
caches.open(cacheName).then(async function(cache) {
let cacheAdds = [];
try {
// Get all the files from the uploads listing
const res = await fetch('/uploads');
const { data = [] } = await res.json();
const files = data.map(f => `/uploads/${f}`);
// Cache all uploads files urls
cacheAdds.push(cache.addAll(files));
} catch(err) {
console.warn('PWA:install:fetch(uploads):err', err);
}
// Also add our static files to the cache
cacheAdds.push(cache.addAll(filesToCache));
return Promise.all(cacheAdds);
}),
// Create the sync cache object
caches.open(syncCacheName).then(cache => cache.put(syncName, jsonResponse({
pending: [], // For storing the penging files that later will be synced
deleted: [] // For storing the files that later will be deleted on sync
}))),
])
);
});
Run Code Online (Sandbox Code Playgroud)
self.addEventListener('fetch', function(event) {
// Clone request so we can consume data later
const request = event.request.clone();
const { method, url, headers } = event.request;
event.respondWith(
fetch(event.request).catch(async function(err) {
const { headers, method, url } = event.request;
// A custom header that we set to indicate the requests come from our syncing method
// so we won't try to fetch anything from cache, we need syncing to be done on the server
const xSyncing = headers.get('X-Syncing');
if(xSyncing && xSyncing.length) {
return caches.match(event.request);
}
switch(method) {
case 'GET':
// Handle listing data for /uploads and return JSON response
break;
case 'PUT':
// Handle upload to cache and return success response
break;
case 'DELETE':
// Handle delete from cache and return success response
break;
}
// If we meet no specific criteria, then lookup to the cache
return caches.match(event.request);
})
);
});
function jsonResponse(data, status = 200) {
return new Response(data && JSON.stringify(data), {
status,
headers: {'Content-Type': 'application/json'}
});
}
Run Code Online (Sandbox Code Playgroud)
GETif(url.match(/\/uploads\/?$/)) { // Failed to get the uploads listing
// Get the uploads data from cache
const uploadsRes = await caches.match(event.request);
let { data: files = [] } = await uploadsRes.json();
// Get the sync data from cache
const syncRes = await caches.match(new Request(syncName), { cacheName: syncCacheName });
const sync = await syncRes.json();
// Return the files from uploads + pending files from sync - deleted files from sync
const data = files.concat(sync.pending).filter(f => sync.deleted.indexOf(f) < 0);
// Return a JSON response with the updated data
return jsonResponse({
success: true,
data
});
}
Run Code Online (Sandbox Code Playgroud)
PUT// Get our custom headers
const filename = headers.get('X-Filename');
const mimetype = headers.get('X-Mimetype');
if(filename && mimetype) {
// Get the uploads data from cache
const uploadsRes = await caches.match('/uploads', { cacheName });
let { data: files = [] } = await uploadsRes.json();
// Get the sync data from cache
const syncRes = await caches.match(new Request(syncName), { cacheName: syncCacheName });
const sync = await syncRes.json();
// If the file exists in the uploads or in the pendings, then return a 409 Conflict response
if(files.indexOf(filename) >= 0 || sync.pending.indexOf(filename) >= 0) {
return jsonResponse({ success: false }, 409);
}
caches.open(cacheName).then(async (cache) => {
// Write the file to the cache using the response we cloned at the beggining
const data = await request.blob();
cache.put(`/uploads/${filename}`, new Response(data, {
headers: { 'Content-Type': mimetype }
}));
// Write the updated files data to the uploads cache
cache.put('/uploads', jsonResponse({ success: true, data: files }));
});
// Add the file to the sync pending data and update the sync cache object
sync.pending.push(filename);
caches.open(syncCacheName).then(cache => cache.put(new Request(syncName), jsonResponse(sync)));
// Return a success response with fromSw set to tru so we know this response came from service worker
return jsonResponse({ success: true, fromSw: true });
}
Run Code Online (Sandbox Code Playgroud)
DELETE// Get our custom headers
const filename = headers.get('X-Filename');
if(filename) {
// Get the uploads data from cache
const uploadsRes = await caches.match('/uploads', { cacheName });
let { data: files = [] } = await uploadsRes.json();
// Get the sync data from cache
const syncRes = await caches.match(new Request(syncName), { cacheName: syncCacheName });
const sync = await syncRes.json();
// Check if the file is already pending or deleted
const pendingIndex = sync.pending.indexOf(filename);
const uploadsIndex = files.indexOf(filename);
if(pendingIndex >= 0) {
// If it's pending, then remove it from pending sync data
sync.pending.splice(pendingIndex, 1);
} else if(sync.deleted.indexOf(filename) < 0) {
// If it's not in pending and not already in sync for deleting,
// then add it for delete when we'll sync with the server
sync.deleted.push(filename);
}
// Update the sync cache
caches.open(syncCacheName).then(cache => cache.put(new Request(syncName), jsonResponse(sync)));
// If the file is in the uplods data
if(uploadsIndex >= 0) {
// Updates the uploads data
files.splice(uploadsIndex, 1);
caches.open(cacheName).then(async (cache) => {
// Remove the file from the cache
cache.delete(`/uploads/${filename}`);
// Update the uploads data cache
cache.put('/uploads', jsonResponse({ success: true, data: files }));
});
}
// Return a JSON success response
return jsonResponse({ success: true });
}
Run Code Online (Sandbox Code Playgroud)
// Get the sync data from cache
const syncRes = await caches.match(new Request(syncName), { cacheName: syncCacheName });
const sync = await syncRes.json();
// If the are pending files send them to the server
if(sync.pending && sync.pending.length) {
sync.pending.forEach(async (file) => {
const url = `/uploads/${file}`;
const fileRes = await caches.match(url);
const data = await fileRes.blob();
fetch(url, {
method: 'PUT',
headers: {
'X-Filename': file,
'X-Syncing': 'syncing' // Tell SW fetch that we are synching so to ignore this fetch
},
body: data
}).catch(err => console.log('sync:pending:PUT:err', file, err));
});
}
// If the are deleted files send delete request to the server
if(sync.deleted && sync.deleted.length) {
sync.deleted.forEach(async (file) => {
const url = `/uploads/${file}`;
fetch(url, {
method: 'DELETE',
headers: {
'X-Filename': file,
'X-Syncing': 'syncing' // Tell SW fetch that we are synching so to ignore this fetch
}
}).catch(err => console.log('sync:deleted:DELETE:err', file, err));
});
}
// Update and reset the sync cache object
caches.open(syncCacheName).then(cache => cache.put(syncName, jsonResponse({
pending: [],
deleted: []
})));
Run Code Online (Sandbox Code Playgroud)
我创建了一个实现所有这些的 PWA 示例,您可以在此处找到并测试。我已经使用 Chrome 和 Firefox 以及在移动设备上使用 Firefox Android 对其进行了测试。
您可以在此 Github 存储库中找到该应用程序的完整源代码(包括express服务器):https : //github.com/clytras/pwa-sandbox。
| 归档时间: |
|
| 查看次数: |
3096 次 |
| 最近记录: |