B4J Tutorial [BANanoVuetifyAD3] Create Professional Looking Vuetify WebSites & WebApps with BANano

Mashiane

Expert
Licensed User
Longtime User
Part 41 continued..

You need to create a service worker file after BANano.Build.

NB: The service worker file should reside on the root folder of your web server

B4X:
BANano.Build(Publish)
   
    'on chrome DISABLE: chrome://flags/#enable-native-notifications
    'add firebase messaging service worker
    'at root of site.
    File.Copy(File.DirAssets, "firebase-logo.png", Publish, "firebase-logo.png")
    'create the service worker file
    Dim fbm As String = File.Combine(Publish, "firebase-messaging-sw.js")
   
File.WriteString("", fbm, $"//self.addEventListener("notificationclose", console.log);
//self.addEventListener("notificationclick", console.log);

importScripts("https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js");
importScripts("https://www.gstatic.com/firebasejs/8.2.1/firebase-analytics.js");

var firebaseConfig = {
    apiKey: "(redacted)",
    authDomain: "(redacted)",
    projectId: "(redacted)",
    storageBucket: "(redacted)",
    messagingSenderId: "(redacted)",
    appId: "(redacted)",
    measurementId: "(redacted)"
};

firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

messaging.onBackgroundMessage(function(payload) {
  console.log('service worker', payload);
  const notification = payload.notification;
  const notificationTitle = notification.title;
  const notificationOptions = {
    body: notification.body,
    icon: '/firebase-logo.png',
    tag: 'fb'
    requireInteraction: true,
  };
  return self.registration.showNotification(notificationTitle, notificationOptions);
});"$)
 
Last edited:

Mashiane

Expert
Licensed User
Longtime User
Part 41 Continued

Our next step is to try and attempt to send messages via the client. We will use a token to do this and send the message using BANanoFetch. This will send a message which can be received when the app has the focus or in background (latter not tested yet)

You can create your user interface to do this anyway you want of course...

1. Get the registered token to send a message to.




We can then use Push.JS to show the notification on the client side when the app runs in the foreground!

B4X:
'use fetch
    Dim response As BANanoFetchResponse
    Dim error As BANanoObject
    Dim data As BANanoJSONParser
  
    Dim options As BANanoFetchOptions
    options.Initialize
    options.Method = "POST"
    '
    'lets define the headers
    Dim hdrs As Map = CreateMap()
    hdrs.Put("Content-Type", "application/json;")
    hdrs.Put("Authorization", "key=" & firebase.serverkey)
    options.Headers = hdrs
    '
    'lets define the notification
    Dim notification As Map = CreateMap()
    notification.put("title", stitle)
    notification.Put("body", smessage)
    notification.Put("icon", "./assets/firebase-logo.png")
    'lets define the body of the fetch
    Dim body As Map = CreateMap()
    body.put("to", stoken)
    body.put("notification", notification)
    options.Body = banano.ToJson(body)
       
    Dim fetch As BANanoFetch
    fetch.Initialize("https://fcm.googleapis.com/fcm/send", options)
    fetch.Then(response)
    fetch.Return(response.json)
    fetch.Then(data)
    Dim res As Map = data.NextObject
    Dim results As List = res.get("results")
    If results.Size > 0 Then
        Dim result As Map = results.Get(0)
        Dim smessage_id As String = result.Get("message_id")
        vuetify.ShowSnackBarSuccess("Message ID: " & smessage_id)
    End If
    fetch.Else(error)
    Log(error)
    fetch.End

To be continued...
 

Mashiane

Expert
Licensed User
Longtime User
Part 41 continued.

To show the notification at client side, we write some code. Thanks to stack over-flow.

B4X:
messaging.onMessage(function(payload) {
    console.log("onMessage: ", payload);
    navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
        registration.showNotification(
            payload.notification.title,
            payload.notification
        )
    });
});

We write this in BANano as...

B4X:
'when a message is received when app has focus
'Reference: https://stackoverflow.com/questions/40411059/create-firebase-notification-with-page-in-foreground-focus/60247902#60247902
Sub onMessage(payload As Map)
    Log("foreground: onMessage...")
    Log(payload)
    Dim notification As Map = payload.Get("notification")
    Dim sbody As String = notification.Get("body")
    Dim sicon As String = notification.Get("icon")
    Dim stitle As String = notification.Get("title")
    '
    Dim nav As BANanoNavigator = banano.Navigator
   
    Dim registration As BANanoObject
    Dim swe As Map
    Dim swr As BANanoPromise = nav.GetField("serviceWorker").RunMethod("getRegistration", "/firebase-cloud-messaging-push-scope")
    banano.Await(swr)
    swr.Then(registration)
    Dim notificationOptions As Map = CreateMap()
    notificationOptions.Put("body", sbody)
    notificationOptions.Put("icon", "./assets/firebase-logo.png")
    notificationOptions.Put("requireInteraction", True)
    notificationOptions.Put("putvibrate", Array(300, 100, 400))
    '
    registration.RunMethod("showNotification", Array(stitle, notificationOptions))
   
    swr.Else(swe)
    vuetify.ShowSnackBarError("We could not show the notification...")
    Log(swe)
    swr.End
End Sub

Enjoy!
 

Mashiane

Expert
Licensed User
Longtime User
Version 2.90 BETA Releases.

1. Important bug fix with .GetData where propety uses a .
2. Switch fix.



By default, when the switch does not have a color specified, it uses a "primary" color.

The second switch here a "success" specification for the color. So one can really "see" when OFF and ON.

Download
 
Last edited:

joulongleu

Active Member
Licensed User
Longtime User
Hi:?@Mashiane :
After trying for a long time, although I can generate the code, I still don’t know how to use it
1. Is there a video to learn?
2. Whether to generate MSSQLCRUD?
 

Attachments

  • users.txt
    9.8 KB · Views: 320
  • 1609661185297.png
    317.8 KB · Views: 258

Mashiane

Expert
Licensed User
Longtime User
After trying for a long time, although I can generate the code, I still don’t know how to use it
There is no video for the MySQLCRUD class, however in that post, I did indicate how one needs to use the code.



Assumptions:

1. You have defined mysqlconfig.php to connect to your database, this database should be named "test"
2. You have a database named "test" and a table named "user"
3. You have used the schema indicated in the MySQLCRUD you have defined to create the users table.
4. You have created the ViewMySQLUsers code module in B4X.
5. You run the above code in BANano_Ready (comment out pgIndex.Initialize)
6. Copy the generated text file contents to ViewMySQLUsers code module as is.
7. Comment the code to create text file on BANano_Ready and uncomment pgIndex.Initialize
8. In AddRouters, add ViewMySQLUsers.Initialize
9. On the links, add an additional link to point to ViewMySQLUsers.
10. Run the application,

I will attempt to have a demo video sometime..

Ta!
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…