必须在辅助脚本的初始评估中添加事件处理程序

时间:2018-07-08 18:25:41

标签: javascript push push.js

我在npm的帮助下安装了该插件,并尝试使用它,但是出现以下错误:

“ push”事件的事件处理程序必须添加到辅助脚本的初始评估中

'pushsubscriptionchange'事件的事件处理程序必须添加到工作脚本的初始评估中。

必须在辅助脚本的初始评估中添加'notificationclick'事件的事件处理程序。

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',
            }
        ])
    ]

};

代码:

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);
}

请问,有什么想法吗?

0 个答案:

没有答案