Service worker and payment Handlers - service-worker

I created a service worker for a payment manager. When I checked the server is installed but I do not see the payment methods installed on the browser.
i added the event install fetch and load but i can't show the payment methods register in browser..
Any help please
My installer is
navigator.serviceWorker.register('sw.js').then(() => {
return navigator.serviceWorker.ready;
}).then((registration) => {
if (!registration.paymentManager) {
console.log('No payment handler capability in this browser. Is chrome://flags/#service-worker-payment-apps enabled?');
return;
}
if (!registration.paymentManager.instruments) {
return;
}
registration.paymentManager.instruments
.set('instrument-key', {
name: 'Chrome uses name and icon from the web app manifest',
enabledMethods: ['https://...'],
method: 'https://...',
})
.then(() => {
registration.paymentManager.instruments.get('instrument-key').then((instrument) => {
}).catch(...
})
My server worker
let payment_request_event;
let resolver;
let client;
const addResourcesToCache = async (resources) => {
const cache = await caches.open("v1");
await cache.addAll(resources);
};
self.addEventListener('install', event => {
event.waitUntil(
addResourcesToCache([
"/",
"/index.html",
])
);
console.log(`SW: Event fired: ${event.type}`);
console.dir(event);
});
self.addEventListener('activate', event => {
console.dir(event);
});
self.addEventListener('fetch', event => {
event.respondWith(fetch(event.request));
});
self.addEventListener('canmakepayment', e => {
console.log('canmakepayment', e);
e.respondWith(true);
});
self.addEventListener('paymentrequest', async e => {
console.log(e)
payment_request_event = e;
e.respondWith(resolver.promise);
// Open the checkout page.
try {
// Open the window and preserve the client
client = await e.openWindow('https://...html');
...

Related

Cordova Plugin Purchase - redirect after successful subscription

I am using this plugin (https://github.com/j3k0/cordova-plugin-purchase) to handle a in app subscription.
iap.validator = "https://validator.fovea.cc/v1/validate?appName=XXX";
//initiate initInAppPurchase function
useEffect(() => {
const init = async () => {
await initInAppPurchase();
}
init();
}, []);
//if on an ios or android device, then get product info
const initInAppPurchase = () => {
if ((isPlatform('ios')) || (isPlatform('android'))) {
iap.verbosity = iap.DEBUG;
iap.register({
id: "tpmonthly",
alias: "Monthly",
type: iap.PAID_SUBSCRIPTION
});
iap.ready(() => {
let product = iap.get('Monthly');
setPrice(product.price)
setProduct(product)
})
iap.refresh();
}
}
//if user clicks purchase button
const purchaseProduct = () => {
if (product.owned) {
alert('A subscription is currently active.')
} else {
iap.order('Monthly').then(() => {
iap.when("tpmonthly").approved((p: IAPProduct) => {
p.verify();
});
iap.when("tpmonthly").verified((p: IAPProduct) => {
p.finish();
history.push("/ios-signup/");
});
})
}
}
return (
<Button size="large" variant="outlined" onClick={purchaseProduct}>Subscribe Monthly for {productPrice}</Button>
);
What I am hoping to get is that once the subscription is verified that it then redirects the app to /ios-signup/ .. this is not happening.
Is this code correct? And why would it not redirect after p.finish?

FetchEvent.respondWith received an error: Returned response is null

I created a pwa site which is working totally fine in android devices both online and offline. But it is throwing error FetchEvent.respondWith received an error: Returned response is null when tried to load on IOS device with safari 13.0 if the mobile device is offline.
Here is my code snippet from service_worker.js
// install event
self.addEventListener('install', evt => {
evt.waitUntil(
caches.open(staticCacheName).then((cache) => {
return cache.addAll(assets);
})
);
});
// activate event
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then((keyList) => {
return Promise.all(keyList.map((key) => {
if(key !== staticCacheName) {
return caches.delete(key);
}
}));
})
);
});
//fetch event
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request).catch(function() {
return caches.match(event.request,{ignoreSearch: true});
})
);
});
Please, help me find the solution.

iOS PWA 'added to home screen' cache is expiring after a day

I'm building an installable PWA from a CRA. I've added a custom service worker that caches all external requests using the service worker cache API. After the first request, I can toggle my phone onto airplane mode and the app still works, however when I leave the app installed on my phone for a day and come back, the app no longer works in offline mode and instead shows the "Safari cannot open the page because your iPhone is not connected to the internet".
Does an installed PWA on iOS have a cache expiry? Am I doing something wrong?
Here is my service worker code:
const PRECACHE = "precache-v1";
const RUNTIME = "runtime-v2";
const PRECACHE_URLS = [];
this.addEventListener("install", event => {
event.waitUntil(
caches
.open(PRECACHE)
.then(cache => cache.addAll(PRECACHE_URLS))
.then(this.skipWaiting())
);
});
this.addEventListener("activate", event => {
const currentCaches = [PRECACHE, RUNTIME];
event.waitUntil(
caches
.keys()
.then(cacheNames => {
return cacheNames.filter(cacheName => !currentCaches.includes(cacheName));
})
.then(cachesToDelete => {
return Promise.all(
cachesToDelete.map(cacheToDelete => {
return caches.delete(cacheToDelete);
})
);
})
.then(() => this.clients.claim())
);
});
this.addEventListener("fetch", event => {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if (cachedResponse) {
return cachedResponse;
}
return caches.open(RUNTIME).then(cache => {
return fetch(event.request).then(response => {
return cache.put(event.request, response.clone()).then(() => {
return response;
});
});
});
})
);
});

Service worker registers on every sub-URL

I have a site with a service worker and it registers every time a new sub-URL is visited. Is this the expected behaviour?
Example. My root URL is mysite.com. The SW registers OK when I visit that URL. When I visit mysite.com/subpage, it registers as a new service worker for that URL too.
Please tell me if I am doing something wrong or if this is the way the SWs work.
My service worker recache the resources everytime it installs, so I'm guessing it is recaching everything everytime the user visits a sub-URL for the first time. Isn't that not recommended?
This is my SW.
var staticCacheName = "bspev-v" + new Date().getTime();
var filesToCache = [
'/',
'/offline',
'/css/app.css',
'/js/app.js',
'/js/rutas.js',
// iconos app
'/images/icons/icon-72x72.png',
'/images/icons/icon-96x96.png',
'/images/icons/icon-128x128.png',
'/images/icons/icon-144x144.png',
'/images/icons/icon-152x152.png',
'/images/icons/icon-192x192.png',
'/images/icons/icon-384x384.png',
'/images/icons/icon-512x512.png',
'/favicon.ico',
// imagenes app
'/images/logotexto.png',
'/images/offline.png',
// ajax
'/api/prestamos/pendientes',
//fuentes app
'https://fonts.googleapis.com/css?family=Archivo+Narrow&display=swap',
'https://fonts.gstatic.com/s/archivonarrow/v11/tss0ApVBdCYD5Q7hcxTE1ArZ0bbwiXw.woff2',
// vue
'/js/vue.js',
'/js/vue.min.js',
// fontawesome
'/css/fa-all.css',
'/webfonts/fa-solid-900.woff2'
];
// Cache on install
self.addEventListener("install", event => {
this.skipWaiting();
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
console.log('Service Worker instalado.');
return cache.addAll(filesToCache);
})
)
});
// Clear cache on activate
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames
.filter(cacheName => (cacheName.startsWith("bspev-")))
.filter(cacheName => (cacheName !== staticCacheName))
.map(cacheName => caches.delete(cacheName))
);
})
);
});
// Serve from Cache
self.addEventListener("fetch", event => {
const requestURL = new URL(event.request.url);
//Handle api calls
if (/\/api\//.test(requestURL.pathname)) {
event.respondWith(
fetch(event.request).then(response => {
event.waitUntil(
caches.open(staticCacheName).then(cache => {
cache.put(event.request, response.clone());
})
);
return response.clone();
}).catch(function() {
return caches.match(event.request);
})
);
} else {
event.respondWith(
caches.match(event.request)
.then(response => {
return response || fetch(event.request);
})
.catch(() => {
return caches.match('offline');
})
);
}
});
This is the SW registration
<script type="text/javascript">
// Initialize the service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/serviceworker.js', {
scope: '.'
}).then(function (registration) {
// Registration was successful
console.log('Laravel PWA: ServiceWorker registration successful with scope: ', registration.scope);
}, function (err) {
// registration failed :(
console.log('Laravel PWA: ServiceWorker registration failed: ', err);
});
} else { console.log('no serviceWorker in navigator') }
</script>

Fetching service worker

HI i'm trying to create a service worker with autodesk forge viewer, INSTALL and ACTIVATE work but fetching not.
here is my Service worker
const cacheName = 'v1';
const cacheAssets = [
"/index.html",
"/css/main.css",
"/img/myAwesomeIcon.png",
"/js/ForgeTree.js",
"/js/ForgeViewer.js",
"/js/myawesomeextension.js",
"/js/sw.js",
];
self.addEventListener('install', e => {
console.log('service worker: installed');
e.waitUntil(
caches
.open(cacheName)
.then(cache => {
console.log('service worker: caching files');
cache.addAll(cacheAssets);
})
.then(() => self.skipWaiting())
);
});
self.addEventListener('activate', e => {
console.log('service worker: activated');
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if(cache !== cacheName) {
console.log('service worker: clearing old cache');
return caches.delete(cache);
}
})
);
})
);
});
self.addEventListener('fetch', e => {
console.log(e);
});
what i trying is making my own "disconnected workflow" fetching the posts and caching all the models to view them offline form bim360docs, a360 and using the 2leg forge tutorial.
try to fetch anything with the Browsers Fetch API:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Resources