Skip to content

Custom worker scope and path #36

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,33 @@ oneSignal: {
}
```

## Change Worker Path and Scope

By default OneSignal expects you to put `OneSignalSDKWorker.js` in the root of your website (nuxt static folder). In case you're already using `@nuxt/pwa` with the `workbox` module, you already should have a service worker there. Two workers can't have the same scope.

That is why this module changes the scope of `OneSignalSDKWorker.js` to `/_push_/onesignal/`. You can use options to customize path, scope, and filenames.

```js
oneSignal: {
filesPath: '', // set to your path if you put worker files into a subdir, for example '/_push_/onesignal/'
workerFile: 'OneSignalSDKWorker.js',
updaterFile: 'OneSignalSDKUpdaterWorker.js',
swParams: {
scope: '/_push_/onesignal/' // set to an empty string ('') if you want OneSignal to be your main worker
}
}
```

Be sure to use the same settings in OneSignal. See [Service Worker Customizations (path and scope)](https://documentation.onesignal.com/docs/onesignal-service-worker-faq#sdk-parameter-reference-for-service-workers)

## References

- [Web Push SDK Reference](https://documentation.onesignal.com/docs/web-push-sdk) - Available options and API calls
- [Customize Permission Messages](https://documentation.onesignal.com/docs/customize-permission-messages)
- [Thanks for Subscribing Notifications](https://documentation.onesignal.com/docs/welcome-notifications)
- [Product overview](https://documentation.onesignal.com/docs/product-overview) - More info about OneSignal
- [Web Push SDK Setup](https://documentation.onesignal.com/docs/web-push-sdk-setup-https) - Setup guides for in-depth reading what this modules does.
- [Service Worker Customizations (path and scope)](https://documentation.onesignal.com/docs/onesignal-service-worker-faq#sdk-parameter-reference-for-service-workers)

## License

Expand Down
2 changes: 1 addition & 1 deletion example/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1 @@
OneSignalSDK*
*.js
8 changes: 7 additions & 1 deletion example/nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ export default {
oneSignal: {
init: {
appId: 'd867ac26-f7be-4c62-9fdd-b756a33c4a8f'
}
},
workerFile: 'OneSignalSDKWorker.js',
updaterFile: 'OneSignalSDKUpdaterWorker.js',
swParams: {
scope: ''
},
filesPath: ''
}
}
56 changes: 33 additions & 23 deletions lib/module.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import path from 'path'
import { writeFileSync, readFileSync } from 'fs'
import { writeFileSync, readFileSync, mkdirSync } from 'fs'
import hasha from 'hasha'
import defu from 'defu'
import { getRouteParams, joinUrl } from './utils'
Expand All @@ -17,25 +17,29 @@ export default function nuxtOneSignal (oneSignalOptions) {
}

function addOneSignal (oneSignalOptions) {
const { publicPath } = getRouteParams(this.options)
const context = this
const { publicPath } = getRouteParams(context.options)

// Merge options
const defaults = {
OneSignalSDK: undefined,
cdn: true,
GcmSenderId: '482941778795',
importScripts: [
'/sw.js?' + Date.now()
],
init: {
allowLocalhostAsSecureOrigin: true,
welcomeNotification: {
disable: true
}
},
filesPath: '',
workerFile: 'OneSignalSDKWorker.js',
updaterFile: 'OneSignalSDKUpdaterWorker.js',
swParams: {
scope: '/_push_/onesignal/'
}
}

const options = defu({ ...this.options.oneSignal, ...oneSignalOptions }, defaults)
const options = defu({ ...context.options.oneSignal, ...oneSignalOptions }, defaults)

if (options.OneSignalSDK === undefined) {
if (options.cdn) {
Expand Down Expand Up @@ -63,37 +67,43 @@ function addOneSignal (oneSignalOptions) {
}

// Add the oneSignal SDK script to head
if (!this.options.head.script.find(s => s.hid === 'onesignal')) {
this.options.head.script.push({
if (!context.options.head.script.find(s => s.hid === 'onesignal')) {
context.options.head.script.push({
async: true,
src: options.OneSignalSDK,
hid: 'onesignal'
})
}

// Adjust manifest for oneSignal
if (!this.options.manifest) {
this.options.manifest = {}
if (!context.options.manifest) {
context.options.manifest = {}
}
this.options.manifest.gcm_sender_id = options.GcmSenderId

// Adjust swURL option of Workbox for oneSignal
if (!this.options.workbox) {
this.options.workbox = {}
}
this.options.workbox.swURL = 'OneSignalSDKWorker.js'
context.options.manifest.gcm_sender_id = options.GcmSenderId

// Provide OneSignalSDKWorker.js and OneSignalSDKUpdaterWorker.js
const makeSW = (name, scripts) => {
const workerScript = `importScripts(${scripts.map(i => `'${i}'`).join(', ')})\r\n`
writeFileSync(path.resolve(this.options.srcDir, 'static', name), workerScript, 'utf-8')
const {
filesPath: workerDir,
workerFile,
updaterFile
} = options

const staticDir = path.resolve(context.options.srcDir, 'static')

const writeWorker = (fileName, script) => {
const workerScript = `importScripts('${script}')\r\n`
mkdirSync(path.join(staticDir, workerDir), { recursive: true })
writeFileSync(path.join(staticDir, workerDir, fileName), workerScript, 'utf-8')
}

makeSW('OneSignalSDKWorker.js', [].concat(options.importScripts || []).concat(options.OneSignalSDK))
makeSW('OneSignalSDKUpdaterWorker.js', [options.OneSignalSDK])
writeWorker(workerFile, options.OneSignalSDK)
writeWorker(updaterFile, options.OneSignalSDK)

options.workerPath = path.join(workerDir, workerFile)
options.updaterPath = path.join(workerDir, updaterFile)

// Add OneSignal plugin
this.addPlugin({
context.addPlugin({
src: path.resolve(__dirname, '../templates/plugin.js'),
ssr: false,
fileName: 'onesignal.js',
Expand Down
7 changes: 6 additions & 1 deletion templates/plugin.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
window.$OneSignal = window.OneSignal = window.OneSignal || [];

OneSignal.push(['init', <%= JSON.stringify(options.init, null, 2) %>])
OneSignal.push(() => {
OneSignal.SERVICE_WORKER_PARAM = <%= JSON.stringify(options.swParams) %>
OneSignal.SERVICE_WORKER_PATH = <%= JSON.stringify(options.workerPath) %>
OneSignal.SERVICE_WORKER_UPDATER_PATH = <%= JSON.stringify(options.updaterPath) %>
OneSignal.init(<%= JSON.stringify(options.init, null, 2) %>)
})

export default function (ctx, inject) {
inject('OneSignal', OneSignal)
Expand Down
14 changes: 13 additions & 1 deletion test/module.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import { setup, build } from '@nuxtjs/module-test-utils'
import onesignalModule from '..'

const url = path => `http://localhost:3000${path}`
const testPath = '/__pu__/os/'
const testWorkerFile = 'osw.js'
const testUpdaterFile = 'osu.js'

describe('module', () => {
let nuxt, browser
Expand All @@ -18,7 +21,10 @@ describe('module', () => {
oneSignal: {
init: {
appId: 'd867ac26-f7be-4c62-9fdd-b756a33c4a8f'
}
},
filesPath: testPath,
workerFile: testWorkerFile,
updaterFile: testUpdaterFile
}
}

Expand All @@ -40,4 +46,10 @@ describe('module', () => {
expect($OneSignal).toBeDefined()
expect($OneSignal.length).toBe(1)
})

test('worker\'s path is correctly set in OneSignal', async () => {
const page = await browser.page(url('/'))
const workerPath = await page.runScript(() => window.OneSignal.config.userConfig.serviceWorkerPath)
expect(workerPath).toBe(path.join(testPath, testWorkerFile))
})
})