Git Product home page Git Product logo

onesignal-module's Introduction

OneSignal Module

npm version npm downloads Github Actions CI Codecov License

OneSignal is a Free, high volume and reliable push notification service for websites and mobile applications. Setting and using this module is a little tricky as OneSignal requires to register its own Service worker.

Setup

  1. Follow steps to install pwa module

  2. Add @nuxtjs/onesignal dependency to your project

yarn add @nuxtjs/onesignal # or npm install @nuxtjs/onesignal
  1. Add @nuxtjs/onesignal BEFORE @nuxtjs/pwa to the modules section of nuxt.config:
modules: [
  '@nuxtjs/onesignal',
  '@nuxtjs/pwa'
]
  1. Add oneSignal options to nuxt.config:
// Options
oneSignal: {
  init: {
    appId: 'YOUR_APP_ID',
    allowLocalhostAsSecureOrigin: true,
    welcomeNotification: {
        disable: true
    }
  }
}

See references below for all init options.

  1. Add OneSignalSDK* to .gitignore

Async Functions

This module exposes oneSignal as $OneSignal everywhere. So you can call it. Please note that because of async loading of OneSignal SDK script, every action should be pushed into $OneSignal stack.

// Inside page components
this.$OneSignal.push(() => {
    this.$OneSignal.isPushNotificationsEnabled((isEnabled) => {
    if (isEnabled) {
      console.log('Push notifications are enabled!')
    } else {
      console.log('Push notifications are not enabled yet.')
    }
  })
})

// Using window and array form
window.$OneSignal.push(['addListenerForNotificationOpened', (data) => {
  console.log('Received NotificationOpened:', data )}
]);

Change OneSignal SDK Script URL

By default this modules ships with latest SDK dist.

You can use recommended CDN by using cdn: true or changing it to a custom value using OneSignalSDK.

oneSignal: {
  // Use CDN
  cdn: true,

  // Use any custom URL
  OneSignalSDK: 'https://cdn.onesignal.com/sdks/OneSignalSDK.js'
}

References

License

MIT License

onesignal-module's People

Contributors

dimitrifranov avatar geminii avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

onesignal-module's Issues

OneSignal.push works but $nuxt.$OneSignal.push does not

Version

v3.0.0-beta.19

Reproduction link

https://staging.ips-hosting.com

Steps to reproduce

I am having a problem in my production deploy where the callback provided to $nuxt.OneSignal.push() is never called.
Everything works fine in dev.

Environment:

ubuntu: 18.04
node: 12.13
nuxt: 2.10.2
@nuxtjs/pwa: 3.0.0-beta.19
mode: universal

Here are the results of some tests I did in the browser console:

$nuxt.$OneSignal.push(() => { console.log("test") })
undefined
OneSignal.push(() => { console.log("test") })
VM125:1 test
undefined

As you can see $nuxt.$OneSignal.push is not working but OneSignal.push is.

I provided the url to my staging deployment where you can test yourself.

What is expected ?

The callback provided to $nuxt.$OneSignal.push should also be called in production.

What is actually happening?

OneSignal.push works but $nuxt.$OneSignal.push does not.

Additional comments?

If that helps, here is my Dockerfile:

# Base
FROM node:12.13-alpine as base

# Required build args, mapped to environment variables.
# Using a base image allows us to share those environment variables between the builder and the final image.
# This makes sense, because most environment variables are required both during build and during runtime.
ARG URL
ENV URL=$URL
ARG API_URL
ENV API_URL=$API_URL
ARG GA_TRACKING_ID
ENV GA_TRACKING_ID=$GA_TRACKING_ID
ARG STRIPE_API_KEY
ENV STRIPE_API_KEY=$STRIPE_API_KEY
ARG PAYPAL_CLIENT_ID
ENV PAYPAL_CLIENT_ID=$PAYPAL_CLIENT_ID
ARG ONESIGNAL_APP_ID
ENV ONESIGNAL_APP_ID=$ONESIGNAL_APP_ID

# Builder
FROM base as builder

WORKDIR /home/node/app

COPY .npmrc .
COPY package*.json ./
RUN npm install

COPY . .
RUN npm run build && npm prune --production

# Final image
FROM base

RUN apk add --update --no-cache curl

USER node

RUN mkdir /home/node/app
WORKDIR /home/node/app

ENV NODE_ENV=production

EXPOSE 3000/tcp

COPY --from=builder --chown=node:node /home/node/app/.nuxt ./.nuxt
COPY --from=builder --chown=node:node /home/node/app/server-middleware ./server-middleware
COPY --from=builder --chown=node:node /home/node/app/static ./static
COPY --from=builder --chown=node:node /home/node/app/workbox ./workbox
COPY --from=builder --chown=node:node /home/node/app/nuxt.config.js .
COPY --from=builder --chown=node:node /home/node/app/package.json .
COPY --from=builder --chown=node:node /home/node/app/node_modules ./node_modules
COPY --from=builder --chown=node:node /home/node/app/healthcheck.sh ./healthcheck.sh

HEALTHCHECK \
  --interval=15s \
  --timeout=3s \
  --retries=3 \
  CMD /bin/sh /home/node/app/healthcheck.sh

CMD ["npm", "start"]

OneSignalSDK* is added to my .dockerignore.

This bug report is available on Nuxt community (#c178)

Installing service worker failed TypeError: NetworkError: Load failed

I have a PWA in Nuxt 2, when I try to suscribe in an IOS device in Safari I got this error on the console:
[Service Worker Installation] Installing service worker failed TypeError: NetworkError: Load failed

It looks like is something related with the code trying to get the path of the worker: config.workerPath.getFullPath()
Captura de pantalla 2024-05-03 a la(s) 8 21 07 p m

Error when phone is sleeping

"This site has been updated in the background" -- chrome shows this when the phone is locked, but showing when the phone is not locked

Workbox outputted to wrong directory when generating SPA

Version

v2.3.0

Reproduction link

https://codesandbox.io/s/m3kkj8o588

Steps to reproduce

Use a basic Nuxt.js template. Add the @nuxtjs/pwa module. Run nuxt generate.

What is expected ?

The workbox file is generated in dist/_nuxt.

What is actually happening?

The file is generated, but is instead placed in .nuxt/dist.

Additional comments?

This appears to be the correct location for the file when using the build command. But it still uses this directory when generating a SPA resulting in the not being found by the service worker.

This bug report is available on Nuxt community (#c60)

PWA module and OneSignal module do not work together

Failed to execute 'importScripts' on 'WorkerGlobalScope'
Failed to register a ServiceWorker for scope: ServiceWorker script evaluation failed

I get those errors every time, tried every possible solution like setting swURL inside pwa options but it seems like nothing changes at all.

Is there anything I can do as a workaround with this issue or we need to wait for an update?

Infinite reload loop after allowing notifications

    "@nuxtjs/onesignal": "^3.0.0-beta.16",
    "@nuxtjs/pwa": "^3.0.2",
    "nuxt": "^2.14.6"

Whether I have notifyButton set in my nuxt.config.js or I use this.$OneSignal.showSlidedownPrompt(), after I select "Allow" in the native prompt, the browser infinitely reloads. If I reset the "Notifications" setting back to "Ask", the issue goes away. Happening in both Chrome and Firefox

e.$OneSignal.on is not a function

I'm working on a project that uses @nuxtjs/pwa along with @nuxtjs/onesignal and I am having an issue while setting up a listener to the subscriptionChange event on mounted inside of my default layout component. Sometimes it throws e.$OneSignal.on is not a function and I can't get why. On the setup, I've added the onesignal module before the pwa as the documentation says. This is what I'm doing in my component:

mounted() {
    this.$OneSignal.push(() => {
      this.$OneSignal.on('subscriptionChange', isSubscribed => {
        if (isSubscribed) {
          this.$OneSignal.getUserId().then(deviceId => this.addDeviceId(deviceId));
        }
      });
    });
},

I've tried to log the this.$OneSignal and when I get the error it prints an array with all the functions that were pushed into this.$OneSignal instead of the OneSignal object with all the methods, which is weird because this code should never be called before loading the script. Any help would be appreciated!

Thanks!

Anyone manage to get this to work with Nuxt 3?

I just get this error
[nuxt] [request error] [unhandled] [500] Cannot read properties of undefined (reading 'mode') 11:32:32 AM
at nuxtOneSignal (./node_modules/@nuxtjs/onesignal/index.js:16:20)

$OneSignal sometimes works in a PROD environment, sometimes not, in DEV enviroment works fine

Version

v3.0.0-beta.19

Reproduction link

https://github.com/nuxt-community/pwa-module

Steps to reproduce

I was create a trusted https on localhost for testing, there working fine with OneSignal.
But, in production environment sometimes working.

If not works, then I got this error, when refresh browser:

one-signal-error.jpg

I don't understand what is wrong?


I call OneSignal in mounted() hook in app layout.

this.$OneSignal.push(() => {

   this.$OneSignal.showNativePrompt();


    this.$OneSignal.isPushNotificationsEnabled((isEnabled) => {
    if (isEnabled) {
      console.log('Push notifications are enabled!')
    } else {
      console.log('Push notifications are not enabled yet.')
    }
  })
});

If I refresh many times the browser, then I got this (only in production):

one-signal-error-2.jpg

What is expected ?

Every page refresh show native prompt to user.

What is actually happening?

Sometimes show, sometimes not showing native prompt.

Additional comments?

I don't understand, why works on DEV env, and why not in PROD env. :-(

Please help!!!

This bug report is available on Nuxt community (#c195)

Which oneSignal sdk should i use ?

I have generated a pwa app from a nuxt app and using oneSignal with web push sdk which has some restrictions (like automatically collapsing of older notifications when new notifications arrive) this can be resolved by using mobile push sdk,
(mobile push sdks are made for andorid apps and chrome web apps) can i use mobile push sdk in my nuxt pwa app?

OneSignal integration discussion

Thanks for the new module. I have a few suggestions regarding subject:

  • add trace or level option to set up log level in config depending on env:
if (process.env.NODE_ENV === 'development') {
  OneSignal.push(() => OneSignal.log.setLevel('trace'))
}
  • add condition or callback whether to init module, e.g. only for authenticated users
  • if some options need to be translated (like welcomeNotification or promptOptions) how to do this in nuxt config?
This question is available on Nuxt.js community (#c14)

Nuxt 3 Support

Hey 👋 It looks like this module hasn't been updated for Nuxt 3. In an effort to improve the developer experience of modules, I've updated the module to clarify that it only supports Nuxt 2.

If Nuxt 3 support is added it will be moved to the https://github.com/nuxt-modules organisation.

Please let me know if you need any help :)

cc: @Geminii

OneSignal loaded twice in built SPA

Version

v3.0.0-beta.12

Reproduction link

https://github.com/motia/nuxt-onesignal-fresh

Steps to reproduce

git clone https://github.com/motia/nuxt-onesignal-fresh.git
yarn
yarn nuxt build

The SPA must be served on the domain other.test, otherwise you must change use your key.

What is expected ?

The script is loaded once form built SPA.

What is actually happening?

onesignal-twice.PNG

Additional comments?

This bug should not be problematic, because the script is loaded from a cdn with long cache.

This bug report is available on Nuxt community (#c106)

window.OneSignal already defined as 'function'!

HI.

I've just installed this module, and when I ran the example snippet:

this.$OneSignal.push(() => { this.$OneSignal.isPushNotificationsEnabled((isEnabled) => { if (isEnabled) { console.log('Push notifications are enabled!'); } else { console.log('Push notifications are not enabled yet.'); } }); });

image

It is similar to #6, but in the I don't see duplicated OneSignal scripts, but two different ones.

Would you know what is potentially the problem?

Subscription (via slidedownprompt) not working on iOS version 17.4

I have developed a web application with the OneSignal-module in Nuxt 2. We use the "slidedownprompt" to register subscribers. However, on iOS devices, after this prompt and the browser push permission question, nothing happens! No new subscription in OneSignal!

It works fine in Chrome and Firefox browsers across desktop computers, as well as on Samsung tablets and smartphones. But not in iOS 17.4.

Are there others who have encountered similar issues? And is there a work-a-round to let this work?
Please let me know.

It's noteworthy that push notifications are still functional on iOS version 17.4(.1), as demonstrated by this example website: https://simple-push-demo.vercel.app/

OneSignal instance is not consistant, when reloading the page

I try to implement the module in my Nuxt page. But it seems it does not work properly every time.

I have setup the nuxt.config.js as follow:

  // One Signal
  oneSignal: {
    init: {
      appId: "****",
      safari_web_id: "web.onesignal.auto.****",
      allowLocalhostAsSecureOrigin: true,
      welcomeNotification: {
        disable: true
      },
      promptOptions: {
        slidedown: {
          prompts: [
            {
              type: "category",
              autoPrompt: true,
              text: {
                actionMessage:
                  "Abonniere verschiedene Themen von ABC und bleibe auf dem Laufenden.",
                acceptButton: "Abonnieren",
                cancelButton: "Später",

                /* CATEGORY SLIDEDOWN SPECIFIC TEXT */
                negativeUpdateButton: "Abbrechen",
                positiveUpdateButton: "Aktualisieren",
                updateMessage:
                  "Ändere dein Abonnement um verschiedene Themen von ABC zu erhalten."
              },
              delay: {
                pageViews: 2,
                timeDelay: 20
              },
              categories: [
                {
                  tag: "portfolio",
                  label: "Portfolio"
                },
                {
                  tag: "projects",
                  label: "Projekte"
                },
                {
                  tag: "general",
                  label: "Generell"
                }
              ]
            }
          ]
        }
      }
    }
  },
  // .....
  modules: [
    // https://go.nuxtjs.dev/axios
    "@nuxtjs/axios",
    "@nuxtjs/onesignal",
    "@nuxtjs/pwa",
    ["vue-scrollto/nuxt", { duration: 300 }]
  ],

And there is an method where I want to show the category slidedown:

async open() {
    console.log(this.$OneSignal)
    try {
        await this.$OneSignal.showCategorySlidedown({ force: true });
    } catch (e) {
        console.error(e);
    }
},

Because when it works, the output of this.$OneSignal instance is:
class Bi{static setDefaultNotificationUrl(e){return Object(d.a)(this,void 0,void 0,function*(){if(!Ri.isValidUrl(e,{allowNull:!0}))throw new InvalidArgumentError.a("url",InvalidArgumentError.b.Malformed);y…

Now when I reload the page and the showCategorySlidedown function does not work, but does not give any warning. Instead I checked the instance again and it looks like an other instance.
OneSignalStubES6 {VERSION: 151508, log: {…}, directFunctionCallsArray: Array(0), preExistingArray: Array(1), on: ƒ, …}

OneSignal Safari - JS error when in production mode and using internally supplied OneSignal SDK

Currently in the latest version of safari, nuxt and this pwa module, when I am using Workbox and Onesignal, I am getting the following error when running the site in production mode with - nuxt build && nuxt start

    Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'p.pushManager.getSubscription')

My setup for the PWA Module with OneSignal and Webpack is the following -

	modules:[
		'@nuxtjs/onesignal',
		'@nuxtjs/pwa',
		'@nuxtjs/browserconfig',
		'@nuxtjs/font-awesome',
		'@nuxtjs/redirect-module',
		'cookie-universal-nuxt',
		['nuxt-sass-resources-loader', '@/assets/scss/layout.scss'],
	],
	meta:{
		nativeUI:true,
		mobileAppIOS:false,
		favicon:true,
		ogHost: process.env.FACEBOOKHOST,
		ogImage: {
		  path: '/fb-share.jpg',
		  width:'1200',
		  height:'630',
		  type:'image/jpg'
		},
		twitterCard: 'summary_large_image',
		twitterCreator: '@',
		twitterSite: '@'
	},
	oneSignal: {
		init: {
		  appId: process.env.ONESIGNALKEY,
		  allowLocalhostAsSecureOrigin: true,
		  welcomeNotification: {
			  disable: true
		  },
		  autoRegister: false,
		  promptOptions: {				  
			  actionMessage: "...",				  
			  acceptButtonText: "...",				  
			  cancelButtonText: "..."
		  }
		}
	}
	build: {
		vendor:[
		  'socket.io-client',
		  'babel-polyfill',
		  'vee-validate',
		  '@xkeshi/vue-countdown',
		  'vue-the-mask',
				'vue-flickity',
		  'moment-timezone',
		  'lottie-web',
		  '~/static/svg-data/bell.json',
		  '~/static/svg-data/bottle.json',
		  '~/static/svg-data/building.json',
		  '~/static/svg-data/clock.json',
		],
		babel:{
		  presets({server}) {
			return [
			  ['vue-app',
				{
				  useBuiltIns: true,
				  targets: server ? { node: 'current' } : {ie: 11, uglify: true}
				}
			  ]
			];
		  }
		},
		postcss: [
		  require('postcss-fixie')(),
		  require('postcss-utilities')(),
		  require('postcss-aspect-ratio')(),
		],
		extractCSS: {
		  allChunks: true
		},
		extend (config, { isDev, isClient }) {
		  if (isDev && isClient) {
			config.module.rules.push({
			  enforce: 'pre',
			  test: /\.(js|vue)$/,
			  loader: 'eslint-loader',
			  exclude: /(node_modules)/
			})
		  }
		}
	},

Any idea how to resolve this error? If I set OneSignal to use their CDN SDK I don't get an error but then I am unable to test on localhost and it doesn't use my init configs.

Example of that config is -

	oneSignal: {
		cdn: true,
		OneSignalSDK: 'https://cdn.onesignal.com/sdks/OneSignalSDK.js',
		init: {
		  appId: process.env.ONESIGNALKEY,
		  allowLocalhostAsSecureOrigin: true,
		  welcomeNotification: {
			  disable: true
		  },
		  autoRegister: false,
		  promptOptions: {				  
			  actionMessage: "...",				  
			  acceptButtonText: "...",				  
			  cancelButtonText: "..."
		  }
		}
	}
This question is available on Nuxt community (#c62)

Failed to load serviceworker.js. The script has unsupported mimetype

Steps to reproduce

nuxt.config.js

  oneSignal: {
    init: {
      appId: "c07236fb-ec62-458d-9d16-0f15d51409e3",
      allowLocalhostAsSecureOrigin: true,
      cdn: true //Doesn't work even if set to false
    }
  },

build and generate nuxt spa.

Expected Behavior

Onesignal sdk must be setup and ready to use

Actual Behavior

Returns error:

[Service Worker Installation] Installing service worker failed SecurityError: Failed to register a ServiceWorker for scope ('https://mywebsite.com/') with script ('https://mywebsite.com/OneSignalSDKWorker.js?appId=xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx'): The script has an unsupported MIME type ('text/html').

Update: Nuxt does not generate OneSignalSDKWorker.js.

Unable to avoid hard coding for one signal app_id in init.

Hi, i am implementing onesignal integration in nuxt js but i am unable to replace the hardcoded one signal ids in nuxt config because i am unable to access environment variables while deploying.

currently my onesignal config looks like this:

oneSignal: {
    cdn: true,
    init: {
      appId: "hard-coded-id",
      safari_web_id: "hard-coded-id",
      allowLocalhostAsSecureOrigin: true,
      welcomeNotification: {
        disable: true,
      },
    }
  },

need to modify it like:

  oneSignal: {
    cdn: true,
    init: {
      appId: process.env.APP_ID,
      safari_web_id: process.env.SAFARI_WEB_ID,
      allowLocalhostAsSecureOrigin: true,
      welcomeNotification: {
        disable: true,
      },
    }
  },

is there any way out?

ServiceWorker being replaced after page reload

I am facing an issue with using the OneSignal module. Sometimes after a page reload the service worker in use is the OneSignalServiceWorker.js, sometimes sw.js with an error in the console

installWorker - SW's 'controllerchange' fired but no state change!

In this case running OneSignal.sendSelfNotification() from the console in the DevTools produces an error

Uncaught (in promise) g: This operation can only be performed after the user is subscribed.
    at Function.<anonymous> (https://cdn.onesignal.com/sdks/OneSignalPageSDKES6.js?v=151104:1:250797)
    at Generator.next (<anonymous>)
    at r (https://cdn.onesignal.com/sdks/OneSignalPageSDKES6.js?v=151104:1:716)

To reproduce the effect I performed the following steps:

npx create-nuxt-app nuxt-test-push-notifications

The settings are as follows:

create-nuxt-app v3.4.0
✨  Generating Nuxt.js project in nuxt-test-push-notifications
? Project name: nuxt-test-push-notifications
? Programming language: JavaScript
? Package manager: Npm
? UI framework: None
? Nuxt.js modules: Progressive Web App (PWA)
? Linting tools: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Testing framework: None
? Rendering mode: Universal (SSR / SSG)
? Deployment target: Server (Node.js hosting)
? Development tools: jsconfig.json (Recommended for VS Code if you're not using typescript)
? What is your GitHub username? martin widmann
? Version control system: Git

After all the setup is done, I changed nuxt.config.js to look like this:

export default {
  server: {
    port: 8080,
    host: '0.0.0.0',
  },
  head: {
    title: 'nuxt-test-push-notifications',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  css: [
  ],

  plugins: [
  ],

  components: true,

  buildModules: [
  ],

  modules: [
    '@nuxtjs/onesignal',
    '@nuxtjs/pwa',
  ],

  oneSignal: {
    init: {
      appId: 'REDACTED',
      allowLocalhostAsSecureOrigin: true,
    }
  },

  pwa: {
    workbox: {
      config: {
        debug: true
      }
    }
  },

  build: {
  }
}

I then run it with npm run build && npm run start to not fall into the self destroying sw mode.

I set up a test project in OneSignal and for local SSL I'm proxying the nodejs server running on localhost:8080 through an Apache with self signed (and registerd) SSL certs running on port 80.

When I reload the page leaving the Application Tab open, I can see the Service Worker being OneSignalServiceWorker.js and directly being replaced by sw.js.

Any idea why I am facing this issue?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Using npm packages for Renovate presets is now deprecated. Please migrate to repository-based presets instead.

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update devdependency husky to v9
  • chore(deps): update devdependency mkdist to v1
  • 🔐 Create all rate-limited PRs at once 🔐

Edited/Blocked

These updates have been manually edited so Renovate will no longer make changes. To discard all commits and start over, click on a checkbox.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/setup-node v1
  • actions/cache v1
  • codecov/codecov-action v1
npm
package.json
  • defu ^3.2.2
  • hasha ^5.2.0
  • @babel/preset-env ^7.12.11
  • @babel/preset-typescript ^7.12.7
  • @nuxt/test-utils ^0.1.2
  • @nuxt/types ^2.14.12
  • @nuxtjs/eslint-config-typescript ^5.0.0
  • @nuxtjs/pwa ^3.3.4
  • eslint ^7.18.0
  • husky ^4.3.8
  • jest ^26.6.3
  • mkdist ^0.1.1
  • nuxt-edge ^2.15.0-26854632.498f8553
  • playwright ^1.8.0
  • siroc ^0.6.3

  • Check this box to trigger a request for Renovate to run again on this repository

getting error many times t.$OneSignal.isPushNotificationsEnabled is not a function

Version

v3.0.0-beta.19

Reproduction link

https://github.com/nuxt-community/pwa-module

Steps to reproduce

i install pwa module to my app normaly with npm i @nuxtjs/pwa @nuxtjs/onesignal use this to my nuxt.config.js

modules: [
  '@nuxtjs/onesignal',
  '@nuxtjs/pwa',
],

// Options
oneSignal: {
  init: {
    appId: 'YOUR_APP_ID', // <- my private key
    allowLocalhostAsSecureOrigin: true,
    welcomeNotification: {
        disable: false
    }
  }
}

and added this to my default.vue layout

mounted() {
    this.$OneSignal.push(() => {
        this.$OneSignal.isPushNotificationsEnabled((isEnabled) => {
        if (isEnabled) {
          this.$OneSignal.getUserId( function(userId) {
              console.log('player_id of the subscribed user is : ' + userId);
              // Make a POST call to your server with the user ID        
          });
        } else {
          console.log('Push notifications are not enabled yet.')
        }
      })
    })
  }

What is expected ?

it should return player_id of the subscribed user is : ' + userId

What is actually happening?

t.$OneSignal.isPushNotificationsEnabled is not a function

Additional comments?

i did try to clear cache and refresh it work first time than again return this error

This bug report is available on Nuxt community (#c170)

OneSignal - How to avoid hardcoded APP_ID ?

Hi...

I'm trying to use OneSignal module but I can't figure out how to avoid hardcoding APP_ID... the documentation shows this example:

oneSignal: {
    init: {
      appId: 'APP_ID',
      allowLocalhostAsSecureOrigin: true,
      welcomeNotification: {
          disable: true
      }
    }
  }

But I need APP_ID to be wired dynamically on runtime (using a promise, maybe) after getting this information from the server (in a spa-mode app).

Is there any way to get it ?

This question is available on Nuxt community (#c91)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.