Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当应用程序处于后台FCM时更新Web应用程序用户界面_Javascript_Service Worker - Fatal编程技术网

Javascript 当应用程序处于后台FCM时更新Web应用程序用户界面

Javascript 当应用程序处于后台FCM时更新Web应用程序用户界面,javascript,service-worker,Javascript,Service Worker,我使用FCM来处理通知,在我需要从firebase messaging sw.js更新我的UI之前,它工作正常,而我的web应用程序在后台 我的第一个问题是:是否可以通过服务人员在后台更新我的web应用UI(当用户不关注web应用时) 第二,如果是,如何进行?因为我尝试了几件事情,但都不起作用,显然我做错了什么,当它起作用时,我的web应用程序就在前台。我做错了什么 我的代码如下 my firebase service sw.js // [START initialize_firebase_in

我使用FCM来处理通知,在我需要从
firebase messaging sw.js
更新我的UI之前,它工作正常,而我的web应用程序在后台

  • 我的第一个问题是:是否可以通过服务人员在后台更新我的web应用UI(当用户不关注web应用时)

  • 第二,如果是,如何进行?因为我尝试了几件事情,但都不起作用,显然我做错了什么,当它起作用时,我的web应用程序就在前台。我做错了什么

  • 我的代码如下

    my firebase service sw.js

    // [START initialize_firebase_in_sw]
    // Give the service worker access to Firebase Messaging.
    // Note that you can only use Firebase Messaging here, other Firebase 
    libraries
    // are not available in the service worker.
    importScripts('https://www.gstatic.com/firebasejs/4.1.1/firebase-app.js');
    importScripts('https://www.gstatic.com/firebasejs/4.1.1/firebase-messaging.js');
    
    
    // My Custom Service Worker Codes
    var CACHE_NAME = 'assembly-v0.1.3.1';
    var urlsToCache = [
        '/',
        'lib/vendors/bower_components/animate.css/animate.min.css',
        'lib/vendors/bower_components/sweetalert/dist/sweetalert.css',
        'lib/css/app_1.min.css',
        'lib/css/app_2.min.css',
        'lib/css/design.css'
    ];
    var myserviceWorker;
    var servicePort;
    
    
    // Install Service Worker
    self.addEventListener('install', function (event) {
        console.log('installing...');
       // Perform install steps
       event.waitUntil(
         caches.open(CACHE_NAME)
         .then(function (cache) {
         console.log('Opened cache');
         return cache.addAll(urlsToCache);
       })
       );
      console.log('installed...');
     });
    
      // Service Worker Active
      self.addEventListener('activate', function (event) {
      console.log('activated!');
      // here you can run cache management
      var cacheWhitelist = [CACHE_NAME];
    
      event.waitUntil(
        caches.keys().then(function (cacheNames) {
           return Promise.all(
            cacheNames.map(function (cacheName) {
               if (cacheWhitelist.indexOf(cacheName) === -1) {
                return caches.delete(cacheName);
               }
            })
          );
        })
      );
    });
    
    
    self.addEventListener('fetch', function (event) {
      event.respondWith(
        caches.match(event.request)
          .then(function (response) {
            // Cache hit - return response
            if (response) {
              return response;
            }
    
            // IMPORTANT: Clone the request. A request is a stream and
            // can only be consumed once. Since we are consuming this
            // once by cache and once by the browser for fetch, we need
            // to clone the response.
            var fetchRequest = event.request.clone();
    
            return fetch(fetchRequest).then(
              function (response) {
                // Check if we received a valid response
                if (!response || response.status !== 200 || response.type !== 'basic') {
                  return response;
                }
    
            // IMPORTANT: Clone the response. A response is a stream
            // and because we want the browser to consume the response
            // as well as the cache consuming the response, we need
            // to clone it so we have two streams.
            var responseToCache = response.clone();
    
            caches.open(CACHE_NAME)
              .then(function (cache) {
                cache.put(event.request, responseToCache);
              });
    
            return response;
          }
        );
      })
      );
    });
    
    self.addEventListener('message', function (event) {
      console.log("SW Received Message: " + event.data);
      // servicePort = event;
      event.ports[0].postMessage("SW Replying Test Testing 4567!");
    });
    
    myserviceWorker = self;
    
    
    // Initialize the Firebase app in the service worker by passing in the
    // messagingSenderId.
    firebase.initializeApp({
      'messagingSenderId': '393093818386'
    });
    
    // Retrieve an instance of Firebase Messaging so that it can handle background
    // messages.
    const messaging = firebase.messaging();
    // [END initialize_firebase_in_sw]
    
    // If you would like to customize notifications that are received in the
    // background (Web app is closed or not in browser focus) then you should
    // implement this optional method.
    // [START background_handler]
    messaging.setBackgroundMessageHandler(function (payload) {
      console.log('[firebase-messaging-sw.js] Received background message ', payload);
     // Customize notification here
     // send to client
     console.log('Sending data to notification');
     try {
          myserviceWorker.clients.matchAll().then(function (clients) {
          clients.forEach(function (client) {
          console.log('sending to client ' + client);
          client.postMessage({
              "msg": "401",
              "dta": payload.data
          });
        })
      });
     } catch (e) {
        console.log(e);
     }
    const notificationTitle = payload.data.title;;
    const notificationOptions = {
       body: payload.data.body,
       icon: payload.data.icon,
       click_action: "value"
    };
    
     return self.registration.showNotification(notificationTitle,
     notificationOptions);
    });
    // [END background_handler]
    

    在我的主javascript文件中,它接收有效负载。当应用程序位于前台时,它将接收它。我主要关心的问题是,当应用程序位于后台时,前台的所有活动都可以正常工作。

    即使您的网站处于打开状态但没有焦点,也可以更新UI。
    当您获得所有客户端列表时,只需添加启用选项
    includeUncontrolled

    例如:

    messaging.setBackgroundMessageHandler(function (payload) {
        console.log('[firebase-messaging-sw.js] Received background message ', payload);
        self.clients.matchAll({includeUncontrolled: true}).then(function (clients) {
           console.log(clients); 
           //you can see your main window client in this list.
           clients.forEach(function(client) {
               client.postMessage('YOUR_MESSAGE_HERE');
           })
         })
    });
    
    在主页面中,只需添加服务人员消息的侦听器。
    例:

    有关更多详细信息,请参阅

    navigator.serviceWorker.addEventListener('message', function (event) {
        console.log('event listener', event);
    });