Nickersoft / push-fcm-plugin

Official Firebase Cloud Messaging plugin for Push.js v1.0 :fire:
https://pushjs.org
42 stars 13 forks source link

Event handler must be added on the initial evaluation of worker script #13

Open 07artem132 opened 6 years ago

07artem132 commented 6 years ago

Hi, I installed the plugin with the help of npm, and I try to use it, however I get the following errors:

Event handler of 'push' event must be added on the initial evaluation of worker script
Event handler of 'pushsubscriptionchange' event must be added on the initial evaluation of worker script.
Event handler of 'notificationclick' event must be added on the initial evaluation of worker script.

package.json

{
  "name": "push-for-new-tickets",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "push-fcm-plugin": "0.0.2",
    "push.js": "^1.0.5",
    "store": "^2.0.12"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-0": "^6.24.1",
    "copy-webpack-plugin": "^4.5.2",
    "path": "^0.12.7",
    "webpack": "^4.15.1",
    "webpack-cli": "^3.0.8"
  },
  "scripts": {
    "build": "webpack --mode=production",
    "dev-watch": "webpack --mode=development  --watch  --progress --display-modules",
    "dev": "webpack --mode=development"
  },
  "author": "",
  "license": "ISC"
}

webpack.config.js:

const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');
const path = require('path');

module.exports = {
    output: {
        filename: 'main.js',
        path: path.resolve(__dirname, 'js')
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['env']
                    }
                }
            }
        ]
    },
    plugins: [
        new CopyWebpackPlugin([
            {
                from: 'node_modules/push.js/bin/serviceWorker.min.js', to: 'serviceWorker.min.js',
            },
            {
                from: 'node_modules/push-fcm-plugin/bin/firebase-messaging-sw.min.js', to: 'firebase-messaging-sw.min.js',
            }
        ])
    ]

};

code:

let Push = require('push.js');
let PushFCM = require('push-fcm-plugin');
Push.extend(PushFCM);

Push.config({
    FCM: {
        apiKey: "hide",
        authDomain: "hide",
        databaseURL: "hide",
        projectId: "hide",
        storageBucket: "hide",
        messagingSenderId: "hide",
        serviceWorkerLocation: "/",
    },
    serviceWorker: '/serviceWorker.js',
    fallback: function (payload) {
        console.log(payload);
        alert('error');
    }
});

Push.FCM().then(function (FCM) {
    FCM.getToken().then(function (token) {
        console.log("Initialized with token " + token);
    }).catch(function (tokenError) {
        throw tokenError;
    });
}).catch(function (initError) {
    throw initError;
});

serviceWorker:

/* eslint eqeqeq: "off", curly: "error" */
'use strict';

function isFunction(obj) {
  return obj && {}.toString.call(obj) === '[object Function]';
}

function runFunctionString(funcStr) {
  if (funcStr.trim().length > 0) {
    var func = new Function(funcStr);
    if (isFunction(func)) {
      func();
    }
  }
}

self.addEventListener('message', function (event) {
  self.client = event.source;
});

self.onnotificationclose = function (event) {
  runFunctionString(event.notification.data.onClose);

  /* Tell Push to execute close callback */
  self.client.postMessage(JSON.stringify({
    id: event.notification.data.id,
    action: 'close'
  }));
}

self.onnotificationclick = function (event) {
  var link, origin, href;

  if (typeof event.notification.data.link !== 'undefined' && event.notification.data.link !== null) {
    origin = event.notification.data.origin;
    link = event.notification.data.link;
    href = origin.substring(0, origin.indexOf('/', 8)) + '/';

    /* Removes prepending slash, as we don't need it */
    if (link[0] === '/') {
        link = (link.length > 1) ? link.substring(1, link.length) : '';
    }

    event.notification.close();

    /* This looks to see if the current is already open and focuses if it is */
    event.waitUntil(clients.matchAll({
      type: "window"
    }).then(function (clientList) {
      var client, full_url;

      for (var i = 0; i < clientList.length; i++) {
        client = clientList[i];
        full_url = href + link;

        /* Covers case where full_url might be http://example.com/john and the client URL is http://example.com/john/ */
        if (full_url[full_url.length - 1] !== '/' && client.url[client.url.length - 1] === '/') {
          full_url += '/';
        }

        if (client.url === full_url && 'focus' in client){
          return client.focus();
        }
      }

      if (clients.openWindow) {
        return clients.openWindow('/' + link);
      }
    }).catch(function (error) {
      throw new Error("A ServiceWorker error occurred: " + error.message);
    }));
  }

  runFunctionString(event.notification.data.onClick);
}

Any ideas what to do?

bitterdev commented 6 years ago

+1 I have installed by bower and got the same problem.