我已经在先前创建的asp.net MVC Web应用程序中添加了PWA。现在,我希望每次打开应用程序时打开添加到主屏幕弹出窗口。我已经附上了在网站中添加pwa的代码。
1)我的AdminLayout.cshtml代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title - PULSE</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
<meta name="description" content="PMS System">
<meta name="author" content="Ashish Durve">
@{ Html.RenderPartial("GoogleAnalytics"); }
<!-- Add to home screen for Safari on iOS -->
@*<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Pulse">
<link rel="apple-touch-icon" href="images/icons/icon-152x152.png">*@
@Styles.Render("~/Content/css")
<link href="../Content/bootstrap/css/bootstrap.css" rel="stylesheet" media="screen">
<link href="../Content/vendors/easypiechart/jquery.easy-pie-chart.css" rel="stylesheet" media="screen">
<link href="~/Content/assets/login_home.css" rel="stylesheet" />
@*Old Fontawsome 4.4.0 reference for old icons which are not included in new fontawsome 5.0.10*@
<link href="../../Content/bootstrap/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
@* New fontawsome 5.0.10 reference*@
<link href="../../Content/assets/fontawesome-all.css" rel="stylesheet" type="text/css" />
<link rel="manifest" href="~/manifest.json"> @*code for pwa manifest*@
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="../Content/vendors/modernizr-2.6.2-respond-1.1.0.min.js"></script>
<script src="../../Content/vendors/jquery-1.9.1.min.js"></script>
<script src="../../Content/bootstrap/js/popper.min.js"></script>
<script src="../../Content/bootstrap/js/bootstrap.min.js"></script>
<script src="../../Content/assets/bootstrap-material-design.js"></script>
<!--/.fluid-container-->
@*<script src="../../Content/vendors/jquery-1.9.1.min.js"></script>
<script src="../../Content/bootstrap/js/bootstrap.min.js"></script>*@
<script src="../../Content/vendors/easypiechart/jquery.easy-pie-chart.js"></script>
<script src="../../Content/assets/scripts.js"></script>
<script src="../../Content/vendors/bootstrap-wysihtml5/lib/js/wysihtml5-0.3.0.js"></script>
<script src="../../Content/assets/rhinoslider-1.05.min.js"></script>
<script src="../../Content/assets/mousewheel.js"></script>
<script src="../../Content/assets/easing.js"></script>
<!-- Material Design fonts -->
<!--<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" type="text/css">-->
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Bootstrap Material Design -->
<link href="../../Content/assets/bootstrap-material-design.css" rel="stylesheet">
<link href="../../Content/assets/ripples.min.css" rel="stylesheet">
@*<link href="../../Content/assets/addtohomescreen.css" rel="stylesheet" />
<script src="../../Content/assets/addtohomescreen.min.js"></script>
<script src="../../Content/assets/addtohomescreen.js"></script>*@
<script src="../../Content/assets/material.js"></script>
@*<script src="../../Content/assets/bootstrap-material-design.js"></script>*@
<script src="../../Content/assets/ripples.min.js"></script>
<!--iphone PWA AppIcon Reference -->
<link rel="apple-touch-icon" href="touch-icon-iphone.png">
<link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad.png">
<link rel="apple-touch-icon" sizes="180x180" href="touch-icon-iphone-retina.png">
<link rel="apple-touch-icon" sizes="167x167" href="touch-icon-ipad-retina.png">
<link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<!--End-->
<!--iphone PWA Splash Screen Reference -->
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="apple-touch-startup-image" href="/launch.png">
<!-- iPhone X (1125px x 2436px) -->
<link rel="apple-touch-startup-image" media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3)" href="/apple-launch-1125x2436.png">
<!-- iPhone 8, 7, 6s, 6 (750px x 1334px) -->
<link rel="apple-touch-startup-image" media="(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2)" href="/apple-launch-750x1334.png">
<!-- iPhone 8 Plus, 7 Plus, 6s Plus, 6 Plus (1242px x 2208px) -->
<link rel="apple-touch-startup-image" media="(device-width: 414px) and (device-height: 736px) and (-webkit-device-pixel-ratio: 3)" href="/apple-launch-1242x2208.png">
<!-- iPhone 5 (640px x 1136px) -->
<link rel="apple-touch-startup-image" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)" href="/apple-launch-640x1136.png">
<!-- iPad Mini, Air (1536px x 2048px) -->
<link rel="apple-touch-startup-image" media="(device-width: 768px) and (device-height: 1024px) and (-webkit-device-pixel-ratio: 2)" href="/apple-launch-1536x2048.png">
<!-- iPad Pro 10.5" (1668px x 2224px) -->
<link rel="apple-touch-startup-image" media="(device-width: 834px) and (device-height: 1112px) and (-webkit-device-pixel-ratio: 2)" href="/apple-launch-1668x2224.png">
<!-- iPad Pro 12.9" (2048px x 2732px) -->
<link rel="apple-touch-startup-image" media="(device-width: 1024px) and (device-height: 1366px) and (-webkit-device-pixel-ratio: 2)" href="/apple-launch-2048x2732.png">
<!--End-->
<script>
$.material.init();
</script>
@*<script>
$(document).ready(function () { $('body').bootstrapMaterialDesign(); });
</script>*@
<style>
@@media all and (display-mode: standalone) {
body {
background-color: yellow;
}
}
</style>
</head>
<body class="pattern">
<div class="container-fluid">
<div class="row-fluid">
<!--/span-->
@RenderBody()
</div>
<footer>
</footer>
</div>
<script type="text/javascript">
var err = 0;
var handleError;
$(document).ready(function () {
//add to home screen code
window.addEventListener("beforeinstallprompt", function (e) {
// log the platforms provided as options in an install prompt
//console.log(e.platforms); // e.g., ["web", "android", "windows"]
e.userChoice.then(function (outcome) {
//console.log(outcome); // either "accepted" or "dismissed"
}, handleError);
});
//window.addEventListener('appinstalled', (evt) => {
// app.logEvent('a2hs', 'installed');
//});
/////////////////////////////////
// //uncomment the below code
// let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
deferredPrompt.prompt();
deferredPrompt.userChoice
.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
//console.log('User accepted the A2HS prompt');
} else {
//console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
window.addEventListener('appinstalled', (evt) => {
app.logEvent('a2hs', 'installed');
});
//// notify the user your app can be installed
// window.addEventListener('beforeinstallprompt', (e) => {
// e.preventDefault();
// deferredPrompt = e;
// // Update UI notify the user they can add to home screen
// btnAdd.style.display = 'block';
// });
//////Show prompt
//btnAdd.addEventListener('click', (e) => {
// // hide our user interface that shows our A2HS button
// btnAdd.style.display = 'none';
// // Show the prompt
// deferredPrompt.prompt();
// // Wait for the user to respond to the prompt
// deferredPrompt.userChoice
// .then((choiceResult) => {
// if (choiceResult.outcome === 'accepted') {
// console.log('User accepted the A2HS prompt');
// } else {
// console.log('User dismissed the A2HS prompt');
// }
// deferredPrompt = null;
// });
//});
$('#slider').rhinoslider({
controlsPlayPause: false,
showControls: 'always',
showBullets: 'always',
controlsMousewheel: false,
prevText: 'Back',
nextText:'Proceed',
slidePrevDirection: 'toRight',
slideNextDirection: 'toLeft',
cycled: 'false',
controlsKeyboard: 'false'
});
$(".rhino-prev").hide();
$('.rhino-next').after('<a class="form-submit" href="javascript:void(0);" >Proceed</a>');
$(".rhino-next").hide();
var info = ["PERSONAL DETAILS","ACCOUNT DETAILS","ORGANIZATION DETAILS"];
var images = ["../../Content/Images/personal-details-icon.png", "../../Content/Images/account-details.png", "../../Content/Images/contact-details.png"];
$('.rhino-bullet').each(function(index){
$(this).html('<p style="margin: 0pt; font-size: 13px; font-weight: bold;"><img src="./img/'+
images[index]+'"></p><p class="bullet-desc">'+info[index]+'</p></a>');
});
});
$('body').on('click', '.form-submit', function(){
// $('.form-submit').on("click",function(){
$('.form-error').html("");
err = 0;
var current_tab = $('#slider').find('.rhino-active').attr("id");
switch(current_tab){
case 'rhino-item0':
step1_validation();
break;
case 'rhino-item1':
step2_validation();
break;
case 'rhino-item2':
step3_validation();
if (err == 0) {
//alert(err);
$("#freeRegister").submit();
}
break;
}
});
var step1_validation = function(){
//var err = 0;
if($('#fname').val() == ''){
$('#fname').parent().find('.form-error').html("Please enter first name.");
err++;
}
if($('#lname').val() == ''){
$('#lname').parent().find('.form-error').html("Please enter last name.");
err++;
}
if ($('#mobile').val() == '') {
$('#mobile').parent().find('.form-error').html("Please enter mobile phone number.");
err++;
}
else {
var x = $('#mobile').val();
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (!x.match(phoneno)) {
$('#mobile').parent().find('.form-error').html("Please enter valid mobile phone number.");
err++;
}
}
if(err == 0){
$(".rhino-active-bullet").removeClass("step-error").addClass("step-success");
$(".rhino-next").show();
$('.form-submit').hide();
$('.rhino-next').trigger('click');
}else{
$(".rhino-active-bullet").removeClass("step-success").addClass("step-error");
}
};
var step2_validation = function(){
//var err = 0;
if ($('#username').val() == '') {
$('#username').parent().find('.form-error').html("Please enter UserName/Email.");
err++;
}
else {
var x = $('#username').val();
var userName = /^([\w-]+(?:\.[\w-]+)*)@@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (!x.match(userName)) {
$('#username').parent().find('.form-error').html("Please enter valid Email.");
err++;
}
if (!checkUserName(x)) {
$('#username').parent().find('.form-error').html("This user is already registered with us.");
err++;
}
}
if($('#pass').val() == ''){
$('#pass').parent().find('.form-error').html("Please enter password");
err++;
}
if ($('#cpass').val() == '') {
$('#cpass').parent().find('.form-error').html("Please enter confirm password.");
err++;
}
else {
var pass = $('#pass').val();
var cpass = $('#cpass').val();
if (pass != cpass) {
$('#cpass').parent().find('.form-error').html("Confirm password should match password field.");
err++;
}
}
if(err == 0){
$(".rhino-active-bullet").removeClass("step-error").addClass("step-success");
$(".rhino-next").show();
$('.form-submit').hide();
$('.rhino-next').trigger('click');
}else{
$(".rhino-active-bullet").removeClass("step-success").addClass("step-error");
}
};
var step3_validation = function(){
//var err = 0;
if($('#orgName').val() == ''){
$('#orgName').parent().find('.form-error').html("Please enter organization name.");
err++;
}
if(err == 0){
$(".rhino-active-bullet").removeClass("step-error").addClass("step-success");
$(".rhino-next").show();
$('.form-submit').hide();
$('.rhino-next').trigger('click');
}else{
$(".rhino-active-bullet").removeClass("step-success").addClass("step-error");
}
};
function checkUserName(userName) {
valid = false;
url = "../Account/VerifyUserName?userName=" + userName;
$.ajax(
{
url: url,
type: "GET",
async: false,
success: function (data, textStatus, jqXHR) {
if (data == "0") {
valid = false;
}
else {
valid = true;
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Failed to get data. Please contact support team.")
return false;
}
});
return valid;
}
</script>
@*<div class="overlay"></div>*@
</body>
</html>
<script>
// code for service worker of pwa start
if ('serviceWorker' in navigator) {
console.log("Will the service worker register?");
navigator.serviceWorker.register('../serviceWorker.js')
.then(function (reg) {
console.log(reg);
console.log("Yes, it did.");
}).catch(function (err) {
console.log("No it didn't. This happened: ", err)
});
}
// code for service worker of pwa end
</script>
<script>
var deferredPrompt;
window.addEventListener('beforeinstallprompt', function (e) {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
showAddToHomeScreen();
});
</script>
2)serviseworker.js
(function () {
'use strict';
var version = 'v1.0::CacheFirstSafe';
var offlineUrl = "../Controller/Account/Login.cshtml"; // <-- Offline/Index.cshtml
var urlsToCache = ['/', offlineUrl]; // <-- Add more URLs you would like to cache.
// Store core files in a cache (including a page to display when offline)
function updateStaticCache() {
return caches.open(version)
.then(function (cache) {
return cache.addAll(urlsToCache);
});
}
function addToCache(request, response) {
if (!response.ok && response.type !== 'opaque')
return;
var copy = response.clone();
caches.open(version)
.then(function (cache) {
cache.put(request, copy);
});
}
function serveOfflineImage(request) {
if (request.headers.get('Accept').indexOf('image') !== -1) {
return new Response('<svg role="img" aria-labelledby="offline-title" viewBox="0 0 400 300" xmlns="http://www.w3.org/2000/svg"><title id="offline-title">Offline</title><g fill="none" fill-rule="evenodd"><path fill="#D8D8D8" d="M0 0h400v300H0z"/><text fill="#9B9B9B" font-family="Helvetica Neue,Arial,Helvetica,sans-serif" font-size="72" font-weight="bold"><tspan x="93" y="172">offline</tspan></text></g></svg>', { headers: { 'Content-Type': 'image/svg+xml' } });
}
}
self.addEventListener('install', function (event) {
event.waitUntil(updateStaticCache());
});
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys()
.then(function (keys) {
// Remove caches whose name is no longer valid
return Promise.all(keys
.filter(function (key) {
return key.indexOf(version) !== 0;
})
.map(function (key) {
return caches.delete(key);
})
);
})
);
});
self.addEventListener('fetch', function (event) {
var request = event.request;
// Always fetch non-GET requests from the network
if (request.method !== 'GET' || request.url.match('../Controller/Account/Login.cshtml')) {
event.respondWith(
fetch(request)
.catch(function () {
return caches.match(offlineUrl);
})
);
return;
}
// For HTML requests, try the network first, fall back to the cache, finally the offline page
if (request.headers.get('Accept').indexOf('text/html') !== -1) {
event.respondWith(
fetch(request)
.then(function (response) {
// Stash a copy of this page in the cache
addToCache(request, response);
return response;
})
.catch(function () {
return caches.match(request)
.then(function (response) {
return response || caches.match(offlineUrl);
});
})
);
return;
}
// cache first for fingerprinted resources
if (request.url.match(/(\?|&)v=/ig)) {
event.respondWith(
caches.match(request)
.then(function (response) {
return response || fetch(request)
.then(function (response) {
addToCache(request, response);
return response || serveOfflineImage(request);
})
.catch(function () {
return serveOfflineImage(request);
});
})
);
return;
}
// network first for non-fingerprinted resources
event.respondWith(
fetch(request)
.then(function (response) {
// Stash a copy of this page in the cache
addToCache(request, response);
return response;
})
.catch(function () {
return caches.match(request)
.then(function (response) {
return response || serveOfflineImage(request);
})
.catch(function () {
return serveOfflineImage(request);
});
})
);
});
})();
4)Manifest.json
{ “ name”:“ Pulse”, “ short_name”:“脉冲”, “ description”:“ Pulse Progressive Web Application”, “图标”:[
{
"src": "../../Content/images/icon16x16.png",
"sizes": "16x16",
"type": "image/png",
"density": 0.25
},
{
"src": "../../Content/images/icon20x20.png",
"sizes": "20x20",
"type": "image/png",
"density": 0.5
},
{
"src": "../../Content/images/icon32x32.png",
"sizes": "32x32",
"type": "image/png"
},
{
"src": "../../Content/images/icon36x36.png",
"sizes": "36x36",
"type": "image/png",
"density": 0.75
},
{
"src": "../../Content/images/icon40x40.png",
"sizes": "40x40",
"type": "image/png"
},
{
"src": "../../Content/images/icon48x48.png",
"sizes": "48x48",
"type": "image/png",
"density": 1.0
},
{
"src": "../../Content/images/icon60x60.png",
"sizes": "60x60",
"type": "image/png"
},
{
"src": "../../Content/images/icon64x64.png",
"sizes": "64x64",
"type": "image/png"
},
{
"src": "../../Content/images/icon72x72.png",
"sizes": "72x72",
"type": "image/png",
"density": 1.5
},
{
"src": "../../Content/images/icon88x88.png",
"sizes": "88x88",
"type": "image/png"
},
{
"src": "../../Content/images/icon96x96.png",
"sizes": "96x96",
"type": "image/png",
"density": 2.0
},
{
"src": "../../Content/images/icon128x128.png",
"sizes": "128x128",
"type": "image/png",
"density": 2.0
},
{
"src": "../../Content/images/icon144x144.png",
"sizes": "144x144",
"type": "image/png",
"density": 3.0
},
{
"src": "../../Content/images/icon172x172.png",
"sizes": "172x172",
"type": "image/png"
},
{
"src": "../../Content/images/icon192x192.png",
"sizes": "192x192",
"type": "image/png",
"density": 4.0
},
{
"src": "../../Content/images/icon196x196.png",
"sizes": "196x196",
"type": "image/png"
},
{
"src": "../../Content/images/icon256x256.png",
"sizes": "256x256",
"type": "image/png"
},
{
"src": "../../Content/images/icon512x512.png",
"sizes": "512x512",
"type": "image/png",
"density": 5.0
},
{
"src": "../../Content/images/icon1024x1024.png",
"sizes": "1024x1024",
"type": "image/png"
}
], “ display”:“独立”, “ theme_color”:“#536878”, “ background_color”:“ #fff”,
“ start_url”:“ /” }