Ank*_*kur 8 c# asp.net progressive-web-apps
我想用 asp.net webforms 创建一个 pwa。我无法理解如何注册 service worker 以及如何使 web 应用程序可用于在线。
DJN*_*DJN 10
对您问题的简短回答是“是”。
我在我的 Web 表单 asp.net 站点上启动并运行了它。
使用 Microsoft PWA 生成器。它超级简单,可以为您节省一些时间。 https://www.pwabuilder.com/
我确实必须将我的 pwabuilder-sw.js 移动到我的根目录才能让它工作。抱歉,这里的简短回答是一步一步的。请阅读代码中的注释。
步骤一:创建manifest.json档案-你可以找到关于Web应用程序清单的更多的信息在这里文件:
https://developers.google.com/web/fundamentals/web-app-manifest
和
HTTPS://developer.mozilla。 org/en-US/docs/Web/Manifest
它最终看起来像这样:
{
"name": "Longer Answer",
"short_name": "Not a short answer",
"start_url": ".",
"display": "standalone",
"background_color": "#fff",
"description": "A simply readable Longer Answer News app.",
"icons": [{
"src": "images/touch/homescreen48.png",
"sizes": "48x48",
"type": "image/png"
}, {
"src": "images/touch/homescreen72.png",
"sizes": "72x72",
"type": "image/png"
}, {
"src": "images/touch/homescreen96.png",
"sizes": "96x96",
"type": "image/png"
}, {
"src": "images/touch/homescreen144.png",
"sizes": "144x144",
"type": "image/png"
}, {
"src": "images/touch/homescreen168.png",
"sizes": "168x168",
"type": "image/png"
}, {
"src": "images/touch/homescreen192.png",
"sizes": "192x192",
"type": "image/png"
}]
}
Run Code Online (Sandbox Code Playgroud)
第二步:创建一个 Service Worker。Service workers 可以让你的站点离线工作,运行得更快,或者两者兼而有之。以下示例将是一个高级缓存服务工作者,它允许您配置以不同方式缓存的文件和路由(预缓存、服务器优先、缓存优先等)。该脚本可用于构建脱机工作的快速应用程序(即使是动态内容)。有关 Service Workers 的更多信息,请访问:https : //developers.google.com/web/fundamentals/primers/service-workers
文件名:register-sw.js
// This is the "Offline page" service worker
// Add this below content to your HTML page, or add the js file to your page at the very top to register service worker
// Check compatibility for the browser we're running this in
if ("serviceWorker" in navigator) {
if (navigator.serviceWorker.controller) {
console.log("[PWA Builder] active service worker found, no need to register");
} else {
// Register the service worker
navigator.serviceWorker
.register("pwabuilder-sw.js", {
scope: "./"
})
.then(function (reg) {
console.log("[PWA Builder] Service worker has been registered for scope: " + reg.scope);
});
}
}
Run Code Online (Sandbox Code Playgroud)
文件名:pwa-sw.js
//This is the service worker with the Advanced caching
const CACHE = "pwabuilder-adv-cache";
const precacheFiles = [
/* Add an array of files to precache for your app */
];
// TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html";
const offlineFallbackPage = "ToDo-replace-this-name.html";
const networkFirstPaths = [
/* Add an array of regex of paths that should go network first */
// Example: /\/api\/.*/
];
const avoidCachingPaths = [
/* Add an array of regex of paths that shouldn't be cached */
// Example: /\/api\/.*/
];
function pathComparer(requestUrl, pathRegEx) {
return requestUrl.match(new RegExp(pathRegEx));
}
function comparePaths(requestUrl, pathsArray) {
if (requestUrl) {
for (let index = 0; index < pathsArray.length; index++) {
const pathRegEx = pathsArray[index];
if (pathComparer(requestUrl, pathRegEx)) {
return true;
}
}
}
return false;
}
self.addEventListener("install", function (event) {
console.log("[PWA] Install Event processing");
console.log("[PWA] Skip waiting on install");
self.skipWaiting();
event.waitUntil(
caches.open(CACHE).then(function (cache) {
console.log("[PWA] Caching pages during install");
return cache.addAll(precacheFiles).then(function () {
if (offlineFallbackPage === "ToDo-replace-this-name.html") {
return cache.add(new Response("TODO: Update the value of the offlineFallbackPage constant in the serviceworker."));
}
return cache.add(offlineFallbackPage);
});
})
);
});
// Allow sw to control of current page
self.addEventListener("activate", function (event) {
console.log("[PWA] Claiming clients for current page");
event.waitUntil(self.clients.claim());
});
// If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener("fetch", function (event) {
if (event.request.method !== "GET") return;
if (comparePaths(event.request.url, networkFirstPaths)) {
networkFirstFetch(event);
} else {
cacheFirstFetch(event);
}
});
function cacheFirstFetch(event) {
event.respondWith(
fromCache(event.request).then(
function (response) {
// The response was found in the cache so we responde with it and update the entry
// This is where we call the server to get the newest version of the
// file to use the next time we show view
event.waitUntil(
fetch(event.request).then(function (response) {
return updateCache(event.request, response);
})
);
return response;
},
function () {
// The response was not found in the cache so we look for it on the server
return fetch(event.request)
.then(function (response) {
// If request was success, add or update it in the cache
event.waitUntil(updateCache(event.request, response.clone()));
return response;
})
.catch(function (error) {
// The following validates that the request was for a navigation to a new document
if (event.request.destination !== "document" || event.request.mode !== "navigate") {
return;
}
console.log("[PWA] Network request failed and no cache." + error);
// Use the precached offline page as fallback
return caches.open(CACHE).then(function (cache) {
cache.match(offlineFallbackPage);
});
});
}
)
);
}
function networkFirstFetch(event) {
event.respondWith(
fetch(event.request)
.then(function (response) {
// If request was success, add or update it in the cache
event.waitUntil(updateCache(event.request, response.clone()));
return response;
})
.catch(function (error) {
console.log("[PWA ] Network request Failed. Serving content from cache: " + error);
return fromCache(event.request);
})
);
}
function fromCache(request) {
// Check to see if you have it in the cache
// Return response
// If not in the cache, then return error page
return caches.open(CACHE).then(function (cache) {
return cache.match(request).then(function (matching) {
if (!matching || matching.status === 404) {
return Promise.reject("no-match");
}
return matching;
});
});
}
function updateCache(request, response) {
if (!comparePaths(request.url, avoidCachingPaths)) {
return caches.open(CACHE).then(function (cache) {
return cache.put(request, response);
});
}
return Promise.resolve();
}
Run Code Online (Sandbox Code Playgroud)
第三步:测试以确保您的新 manifest.json 文件和脚本正常工作。
我知道两种测试 pwa 配置的方法:
打开谷歌开发工具并转到应用程序选项卡。然后在左侧单击 Service Workers。接下来选中顶部“重新加载时更新”的框。之后重新加载您的页面并观察结果。
使用灯塔审计站点。您可以在“审核”选项卡下的谷歌开发人员工具中找到它。
请让我知道,如果你有任何问题。
McM*_*phy -4
您的问题的简短答案是“否”。
只需让 SPA(单页应用程序)启动您的 Service Worker,并回调您的 .Net 控制器即可获取所需的数据/功能。
没有 Razor、网络表单等。
注意:如果有人建议你使用 React-Redux,请尽快远离他们!这是第一手建议,但我确信 Angular 和 Vue 也可以这样说。
| 归档时间: |
|
| 查看次数: |
2889 次 |
| 最近记录: |