Integrate PushBots in Vue Apps
Bassel

For Vue apps with server-side rendering

Mainly Nuxt.js which was used to build Pushbots.com Marketing website and other projects within the company.

You need to add a plugin to nuxt.config.js

plugins: [
  { src: '~/plugins/PB.client.js' }
],

Note the .client in the file name this means “tell Nuxt to run this file ONLY ON THE CLIENT SIDE

Now make a new file under /plugins/ called PB.client.js and paste this code in it

export default ({ app }) => {
  if (process.browser) {
    const PB = window.PB || {}
    PB.q = PB.q || []
    PB.events = PB.events || []
    PB.overlay = true

    if (process.env.NODE_ENV === 'production') {
      PB.app_id = '5c0d38150540a326de518bc5'
      PB.domain = 'https://currencystack.io'
    }

    PB.worker_url = '/custom-worker.js'
    PB.logging_enabled = true
    PB.safari_push_id = 'web.com.pushbots.main'
    // Welcome notification message
    PB.welcome = {
      title: 'Welcome 🙌🎉',
      message: 'Thanks for subscribing!'
    }

    app.router.afterEach((to, from) => {
      if (to.name === 'web') {
        PB.auto_subscribe = true
      }
    })
  }
}

Now replace these values with the App ID you got from app.pushbots.com and the domain your website lives on.

PB.app_id = '5c0d38150540a326de518bc5'
PB.domain = 'https://currencystack.io'

Now we got to call PB.init() which we will do in our default layout

Open this file /layouts/default.vue

And add a mounted life-cycle method with this code in it like this

export default {
  mounted() {
    /* globals PB */
    PB.init()
  }
}

Note the /* globals PB */ this tells ESlint to define a global variable called PB, this helps prevents errors during build, please don’t forget it.

The last thing we need to do is put our worker file and manifest in a public folder that is exposed to the world and in Nuxt that’ll be /static/, do it like this:

And tada you got yourself a working PushBots integration in your Nuxt app.

For Vue apps with only client-side rendering

Like Vue-cli-3 or any other like it

First you’ll need to import //cdn.pushbots.com/js/sdk.min.js at your index.html

//cdn.pushbots.com/js/sdk.min.js

Then you’ll need to go to your App starting point which in most cases will be /src/main.js

Here you’ll need to import the PB.client.js above after creating it of course somewhere like /src/assets/PB.client.js name it any name you like because it doesn’t matter here it only matters in nuxt apps

import "./assets/PB.client.js";

Then in your App.vue or whatever file that is the parent of all other components, make a mounted life-cycle method and call PB.init()

export default {
  mounted() {
    /* globals PB */
    PB.init()
  }
}

And the finale, put the worker and manifest files in your publicly exposed directory.

I.e. In vue-cli-3 this will be /public/

 

Congratulations 🎉 You now have a working PushBots integration. 🙌🎉

Thanks for coming to my TED talk, hope you enjoyed it.


Previous Next