Register Service Worker in Nuxtjs - firebase-cloud-messaging

I am trying to register service worker in my nuxt application.
the problem i am facing is registering the firebase-messaging-sw.js file
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./firebase-messaging-sw.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
}).catch(function(err) {
console.log('Service worker registration failed, error:', err);
});
}
Here is the error i received in the console
Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script

You don't need to register service worker, it's automatically registered.
Also, I didn't found a way to use v9 modular code inside service worker.
Only v8 code works:
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js')
It may have some bugs with this service worker, after each update it stops to work. Looking for another solution... I will consider replace firebase notification with something different.

Related

GCP App Engine - Could not load the default credentials

I'm working on a project, that uses GCP and App Engine. In dev it will print out errors saying:
2020-09-20 15:07:24 dev[development] Error: Could not load the default credentials. Browse
to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (/workspace/node_modules/google-auth-
library/build/src/auth/googleauth.js:161:19) at runMicrotasks (<anonymous>) at
processTicksAndRejections (internal/process/task_queues.js:97:5) at runNextTicks
(internal/process/task_queues.js:66:3) at listOnTimeout (internal/timers.js:518:9)
at processTimers (internal/timers.js:492:7) at async GoogleAuth.getClient
(/workspace/node_modules/google-auth-library/build/src/auth/googleauth.js:503:17) at
async GrpcClient._getCredentials (/workspace/node_modules/google-
gax/build/src/grpc.js:108:24) at async GrpcClient.createStub
(/workspace/node_modules/google-gax/build/src/grpc.js:229:23)
Keep in mind this is development mode, but is running on the GCP App Engine infrastructure, it is not being run on localhost. I'm viewing the logs with the command:
gcloud app logs tail -s dev
According to the GCP App Engine docs # https://cloud.google.com/docs/authentication/production#cloud-console
If your application runs inside a Google Cloud environment that has a default service
account, your application can retrieve the service account credentials to call Google Cloud
APIs.
I checked my app engine service accounts. And I have a default service account and it is active. Please see the redacted image here:
So I guess my question is: If I have an active default service account, and my application is supposed to automatically use the default service account key when it makes API calls, why am I seeing this authentication error? What am I doing wrong?
Edit: here's the code that is printing out errors:
async function updateCrawledOnDateForLink (crawlRequestKey: EntityKey, linkKey: EntityKey): Promise<void> {
try {
const datastore = new Datastore();
const crawlRequest = await datastore.get(crawlRequestKey)
const brand = crawlRequest[0].brand.replace(/\s/g, "")
await data.Link.update(
+linkKey.id,
{ crawledOn: new Date() },
null,
brand)
} catch (error) {
console.error('updateCrawledOnDateForLink ERROR:', `CrawlRequest: ${crawlRequestKey.id}`, `Link: ${linkKey.id}`, error.message)
}
}
My prediction is that creating a new Datastore() each time is the problem, but let me know your thoughts.
The fact that removing new Datastore() from a couple of functions solves the issue indicates that the issue is not with Authentication with App Engine but it is with Datastore, which confirms the documentation piece you shared.
I believe that the issue is that Datastore is getting lost with the credentials when you are creating multiple instances of it in your code for some unknown reason.
Since you mentioned in the comments that you don't really need multiple instances of Datastore in your code the solution to your problem is to use a single instance in a global variable and use that variable in multiple functions.

"Service worker" and notifications when the POST request is cached

I have create a PWA with VueJS and the plugin workbox.
The user can navigate in the application if is offline with the service worker cache.
I cache the request POST and PATCH if the user is offline, but I would like notify the user in this case.
If I use import or require the service worker sends a error message so I cannot use the VueX store to display a message.
Anyone have an idea to solve this problem?

How does vue PWA use the precache? I still get "Page does not work offline"

I have a vue application that I updated to have PWA capability. It uses the firebase messaging service that has overridden the service worker with its own firebase-messaging-sw.js file.
The service worker is registered, active and working, I have added the pwa in the vue.config.js file so that it generates the manifest.json. When you build the production version of the app the following code gets added to the top of the service worker.
importScripts("precache-manifest.7b51ac9589a6dc8041a85d8f1792defa.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
From what I see the percache works fine.
Should this be enough to get the site to work in offline mode?
Do I need to add some cache management myself?
What am I missing because I still get the "Page does not work offline" error message in Chrome's dev tools under the App manifest tab.
Looks like Google also picked up on the quick hack and the warning has returned.
So since of Chrome93 (AUG-2021) the quick hack, will not work anymore :
self.addEventListener('fetch', function(event) {})
Solution working "for now" (since we never know what requirements Google will add later on)
I've found a nice article which provides with a few solutions, the first one the author provides is Network-Falling-Back-To-Cache strategy:
your service worker will first try to retrieve the resource from your server. Then when it can’t do that — because for example, you’re offline — retrieve it from the cache (if it exists there).
self.addEventListener('fetch', function(event) {
event.respondWith(async function() {
try{
var res = await fetch(event.request);
var cache = await caches.open('cache');
cache.put(event.request.url, res.clone());
return res;
}
catch(error){
return caches.match(event.request);
}
}());
});
You can find all the information and alternative solutions in the article:
https://javascript.plainenglish.io/your-pwa-is-going-to-break-in-august-2021-34982f329f40
I hope this will help futur visitors.
Additional side note:
using the above code you might encounter the following error:
service-worker.js:40 Uncaught (in promise) TypeError: Failed to execute 'put' on 'Cache': Request scheme 'chrome-extension' is unsupported
This error is caused by chrome extentions like Augury or Vue dev-tools. Switching both off will cause the error to disappear.
You need to add this line in the serviceworker. It fools the browser into thinking that the page will work offline:
self.addEventListener('fetch', function(event) {}) // add this to fool it into thinking its offline ready

MobileFirst Obtain Access token and Login give no response after setting WL.App.setServerURL

As per my requirement, I am using WL.APP.setServerURL before every login request WLAuthorizationManager.loginof mobilefirst.
When I do first an valid/Invalid login attempt it works fine. As on next attempt I do WL.App.setServerURL, and then WLAuthorizationManager.login (login request) OR WLAuthorizationManager.obtainAccessToken (obtain access token request) don't respond anything. No success and no fail. Although non-secure adapter method works fine.
If I do WL.APP.setServerURL only once on application startup, everything works fine but in between call cause application failure.
let url = ... //fetcht url from adapter call
WL.App.setServerUrl(url, function (sucess) {
WLAuthorizationManager.login(securityCheckName, loginParam).then((data) => {
.... //After login code
}, (response) => {
//Login fail code
});
}, function (error) {
});
Flow :-
I call above code on click of login button.I call a method to get server url from adapter first then I set that url as server url.
When I do an invalid attempt of login it works find for first time, and on next call MFP login, it doesn't respond. Not success nor fail in application.
I am getting error in native logs android.
Android Error logs :-
E/SecurityCheckChallengeHandler(30199): SecurityCheckChallengeHandler.submitChallengeAnswer in SecurityCheckChallengeHandler.java:51 :: submitAnswer has been called for unknown request
.
MobileFirst server version :- 8.0.0.00-20170911-123510
MobileFirst Cordova(plugin) version :- 8.0.2017102403
The WL.App.setServerUrl API is meant to be used sparingly whenever the app needs to connect to a server other than the one defined in mfpclient.properties. If you want to keep the server URL constant, you should just put it up in the mfpclient.properties.
Having said that, the behaviour you mention is not expected - can you update your question with a code snippet of your app performing login & setServerUrl

Meteor: setup accounts-github not working

I'm trying to setup authentication using github.
I followed the documentation. I've installed the packages:
$> meteor add accounts-github
$> meteor add service-configuration
And my code in server/github.js looks like:
ServiceConfiguration.configurations.remove({
service: "github"
});
ServiceConfiguration.configurations.insert({
service: "github",
clientId: '****',
secret: '*************'
});
Meteor.loginWithGithub({
requestPermissions: ['user', 'public_repo']
}, function (err) {
if (err)
Session.set('errorMessage', err.reason || 'Unknown error');
});
When I start meteor now I get the following error:
/Users/me/.meteor/tools/5bf1690853/lib/node_modules/fibers/future.js:173
throw(ex);
^
TypeError: Object #<Object> has no method 'loginWithGithub'
at app/server/github.js:11:8
at app/server/github.js:18:3
....
So it seems the Meteor object doesn't have the loginWithGithub method. Any suggestions why?
You are running the code in the /server directory of your app.
Usually you call this code from the web browser to make Meteor display the Github OAuth login dialog.
This is not available on the server since its only meant to work on the browser side. This is why you see this error.
You would usually fire Meteor.loginWithGithub() in the event listener for when they click a button or some UI element to begin the login process.
Another thing to keep in mind is Session (Session.get, Session.set, etc) only work on the client too.
To see which methods run where use the Meteor documentation. In the top corner of each method it shows where the code can run: Client, Server or Anywhere.