onesignal-vue 2.4.1 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts DELETED
@@ -1,1053 +0,0 @@
1
- import Vue from 'vue';
2
-
3
- const ONESIGNAL_SDK_ID = 'onesignal-sdk';
4
- const ONE_SIGNAL_SCRIPT_SRC =
5
- 'https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js';
6
-
7
- // true if the script is successfully loaded from CDN.
8
- let isOneSignalInitialized = false;
9
- // true if the script fails to load from CDN. A separate flag is necessary
10
- // to disambiguate between a CDN load failure and a delayed call to
11
- // OneSignal#init.
12
- let isOneSignalScriptFailed = false;
13
-
14
- const VueApp: any = Vue;
15
-
16
- if (typeof window !== 'undefined') {
17
- window.OneSignalDeferred = window.OneSignalDeferred || [];
18
- addSDKScript();
19
- }
20
-
21
- /* H E L P E R S */
22
-
23
- function handleOnError() {
24
- isOneSignalScriptFailed = true;
25
- }
26
-
27
- function addSDKScript() {
28
- const script = document.createElement('script');
29
- script.id = ONESIGNAL_SDK_ID;
30
- script.defer = true;
31
- script.src = ONE_SIGNAL_SCRIPT_SRC;
32
-
33
- // Always resolve whether or not the script is successfully initialized.
34
- // This is important for users who may block cdn.onesignal.com w/ adblock.
35
- script.onerror = () => {
36
- handleOnError();
37
- };
38
-
39
- document.head.appendChild(script);
40
- }
41
-
42
- /* T Y P E D E C L A R A T I O N S */
43
-
44
- declare module 'vue/types/vue' {
45
- interface Vue {
46
- $OneSignal: IOneSignalOneSignal;
47
- }
48
- }
49
-
50
- declare global {
51
- interface Window {
52
- OneSignalDeferred?: OneSignalDeferredLoadedCallback[];
53
- OneSignal?: IOneSignalOneSignal;
54
- safari?: {
55
- pushNotification: any;
56
- };
57
- }
58
- }
59
-
60
- /* O N E S I G N A L A P I */
61
-
62
- /**
63
- * @PublicApi
64
- */
65
- const init = (options: IInitObject): Promise<void> => {
66
- if (isOneSignalInitialized) {
67
- return Promise.reject(`OneSignal is already initialized.`);
68
- }
69
- if (!options || !options.appId) {
70
- return Promise.reject('You need to provide your OneSignal appId.');
71
- }
72
- if (!document) {
73
- return Promise.reject(`Document is not defined.`);
74
- }
75
-
76
- return new Promise<void>((resolve, reject) => {
77
- window.OneSignalDeferred?.push((OneSignal) => {
78
- OneSignal.init(options)
79
- .then(() => {
80
- isOneSignalInitialized = true;
81
- resolve();
82
- })
83
- .catch(reject);
84
- });
85
- });
86
- };
87
-
88
- /**
89
- * The following code is copied directly from the native SDK source file BrowserSupportsPush.ts
90
- * S T A R T
91
- */
92
-
93
- // Checks if the browser supports push notifications by checking if specific
94
- // classes and properties on them exist
95
- function isPushNotificationsSupported() {
96
- return supportsVapidPush() || supportsSafariPush();
97
- }
98
-
99
- function isMacOSSafariInIframe(): boolean {
100
- // Fallback detection for Safari on macOS in an iframe context
101
- return (
102
- window.top !== window && // isContextIframe
103
- navigator.vendor === 'Apple Computer, Inc.' && // isSafari
104
- navigator.platform === 'MacIntel'
105
- ); // isMacOS
106
- }
107
-
108
- function supportsSafariPush(): boolean {
109
- return (
110
- (window.safari && typeof window.safari.pushNotification !== 'undefined') ||
111
- isMacOSSafariInIframe()
112
- );
113
- }
114
-
115
- // Does the browser support the standard Push API
116
- function supportsVapidPush(): boolean {
117
- return (
118
- typeof PushSubscriptionOptions !== 'undefined' &&
119
- PushSubscriptionOptions.prototype.hasOwnProperty('applicationServerKey')
120
- );
121
- }
122
- /* E N D */
123
-
124
- /**
125
- * @PublicApi
126
- */
127
- const isPushSupported = (): boolean => {
128
- return isPushNotificationsSupported();
129
- };
130
-
131
- export interface AutoPromptOptions { force?: boolean; forceSlidedownOverNative?: boolean; slidedownPromptOptions?: IOneSignalAutoPromptOptions; }
132
- export interface IOneSignalAutoPromptOptions { force?: boolean; forceSlidedownOverNative?: boolean; isInUpdateMode?: boolean; categoryOptions?: IOneSignalCategories; }
133
- export interface IOneSignalCategories { positiveUpdateButton: string; negativeUpdateButton: string; savingButtonText: string; errorButtonText: string; updateMessage: string; tags: IOneSignalTagCategory[]; }
134
- export interface IOneSignalTagCategory { tag: string; label: string; checked?: boolean; }
135
- export type PushSubscriptionNamespaceProperties = { id: string | null | undefined; token: string | null | undefined; optedIn: boolean; };
136
- export type SubscriptionChangeEvent = { previous: PushSubscriptionNamespaceProperties; current: PushSubscriptionNamespaceProperties; };
137
- export type NotificationEventName = 'click' | 'foregroundWillDisplay' | 'dismiss' | 'permissionChange' | 'permissionPromptDisplay';
138
- export type SlidedownEventName = 'slidedownAllowClick' | 'slidedownCancelClick' | 'slidedownClosed' | 'slidedownQueued' | 'slidedownShown';
139
- export type OneSignalDeferredLoadedCallback = (onesignal: IOneSignalOneSignal) => void;
140
- export interface IOSNotification {
141
- /**
142
- * The OneSignal notification id;
143
- * - Primary id on OneSignal's REST API and dashboard
144
- */
145
- readonly notificationId: string;
146
-
147
- /**
148
- * Visible title text on the notification
149
- */
150
- readonly title?: string;
151
-
152
- /**
153
- * Visible body text on the notification
154
- */
155
- readonly body: string;
156
-
157
- /**
158
- * Visible icon the notification; URL format
159
- */
160
- readonly icon?: string;
161
-
162
- /**
163
- * Visible small badgeIcon that displays on some devices; URL format
164
- * Example: On Android's status bar
165
- */
166
- readonly badgeIcon?: string;
167
-
168
- /**
169
- * Visible image on the notification; URL format
170
- */
171
- readonly image?: string;
172
-
173
- /**
174
- * Visible buttons on the notification
175
- */
176
- readonly actionButtons?: IOSNotificationActionButton[];
177
-
178
- /**
179
- * If this value is the same as existing notification, it will replace it
180
- * Can be set when creating the notification with "Web Push Topic" on the dashboard
181
- * or web_push_topic from the REST API.
182
- */
183
- readonly topic?: string;
184
-
185
- /**
186
- * Custom object that was sent with the notification;
187
- * definable when creating the notification from the OneSignal REST API or dashboard
188
- */
189
- readonly additionalData?: object;
190
-
191
- /**
192
- * URL to open when clicking or tapping on the notification
193
- */
194
- readonly launchURL?: string;
195
-
196
- /**
197
- * Confirm the push was received by reporting back to OneSignal
198
- */
199
- readonly confirmDelivery: boolean;
200
- }
201
-
202
- export interface IOSNotificationActionButton {
203
- /**
204
- * Any unique identifier to represent which button was clicked. This is typically passed back to the service worker
205
- * and host page through events to identify which button was clicked.
206
- * e.g. 'like-button'
207
- */
208
- readonly actionId: string;
209
- /**
210
- * The notification action button's text.
211
- */
212
- readonly text: string;
213
- /**
214
- * A valid publicly reachable HTTPS URL to an image.
215
- */
216
- readonly icon?: string;
217
- /**
218
- * The URL to open the web browser to when this action button is clicked.
219
- */
220
- readonly launchURL?: string;
221
- }
222
-
223
- export interface NotificationClickResult {
224
- readonly actionId?: string;
225
- readonly url?: string;
226
- }
227
-
228
- export type NotificationEventTypeMap = {
229
- 'click': NotificationClickEvent;
230
- 'foregroundWillDisplay': NotificationForegroundWillDisplayEvent;
231
- 'dismiss': NotificationDismissEvent;
232
- 'permissionChange': boolean;
233
- 'permissionPromptDisplay': void;
234
- };
235
-
236
- export interface NotificationForegroundWillDisplayEvent {
237
- readonly notification: IOSNotification;
238
- preventDefault(): void;
239
- }
240
-
241
- export interface NotificationDismissEvent {
242
- notification: IOSNotification;
243
- }
244
-
245
- export interface NotificationClickEvent {
246
- readonly notification: IOSNotification;
247
- readonly result: NotificationClickResult;
248
- }
249
-
250
- export type UserChangeEvent = {
251
- current: UserNamespaceProperties;
252
- };
253
- export type UserNamespaceProperties = {
254
- onesignalId: string | undefined;
255
- externalId: string | undefined;
256
- };
257
-
258
- export interface IInitObject {
259
- appId: string;
260
- subdomainName?: string;
261
- requiresUserPrivacyConsent?: boolean;
262
- promptOptions?: {
263
- slidedown: {
264
- prompts: {
265
- /**
266
- * Whether to automatically display the prompt.
267
- * `true` will display the prompt based on the delay options.
268
- * `false` will prevent the prompt from displaying until the Slidedowns methods are used.
269
- */
270
- autoPrompt: boolean;
271
-
272
- /**
273
- * Only available for type: category. Up to 10 categories.
274
- * @example
275
- * categories: [{ tag: 'local_news', label: 'Local News' }] // The user will be tagged with local_news but will see "Local News" in the prompt.
276
- */
277
- categories: {
278
- /** Should identify the action. */
279
- tag: string;
280
-
281
- /** What the user will see. */
282
- label: string;
283
- }[];
284
-
285
- /**
286
- * The delay options for the prompt.
287
- * @example delay: { pageViews: 3, timeDelay: 20 } // The user will not be shown the prompt until 20 seconds after the 3rd page view.
288
- */
289
- delay: {
290
- /** The number of pages a user needs to visit before the prompt is displayed. */
291
- pageViews?: number;
292
-
293
- /** The number of seconds a user needs to wait before the prompt is displayed.Both options must be satisfied for the prompt to display */
294
- timeDelay?: number;
295
- };
296
-
297
- /**
298
- * The text to display in the prompt.
299
- */
300
- text?: {
301
- /** The callout asking the user to opt-in. Up to 90 characters. */
302
- actionMessage?: string;
303
-
304
- /** Triggers the opt-in. Up to 15 characters. */
305
- acceptButton?: string;
306
-
307
- /** Cancels opt-in. Up to 15 characters. */
308
- cancelMessage?: string;
309
-
310
- /** The message of the confirmation prompt displayed after the email and/or phone number is provided. Up to 90 characters. */
311
- confirmMessage?: string;
312
-
313
- /** Identifies the email text field. Up to 15 characters. */
314
- emailLabel?: string;
315
-
316
- /** Cancels the category update. Up to 15 characters. */
317
- negativeUpdateButton?: string;
318
-
319
- /** Saves the updated category tags. Up to 15 characters. */
320
- positiveUpdateButton?: string;
321
-
322
- /** Identifies the phone number text field. Up to 15 characters. */
323
- smsLabel?: string;
324
-
325
- /** A different message shown to subscribers presented the prompt again to update categories. Up to 90 characters. */
326
- updateMessage?: string;
327
- };
328
-
329
- /**
330
- * The type of prompt to display.
331
- * `push` which is the Slide Prompt without categories.
332
- * `category` which is the Slide Prompt with categories.
333
- * `sms` only asks for phone number.
334
- * `email` only asks for email address.
335
- * `smsAndEmail` asks for both phone number and email address.
336
- */
337
- type: 'push' | 'category' | 'sms' | 'email' | 'smsAndEmail';
338
- }[];
339
- };
340
- };
341
- welcomeNotification?: {
342
- /**
343
- * Disables sending a welcome notification to new site visitors. If you want to disable welcome notifications, this is the only option you need.
344
- */
345
- disabled?: boolean;
346
-
347
- /**
348
- * The welcome notification's message. You can localize this to your own language.
349
- * If left blank or set to blank, the default of 'Thanks for subscribing!' will be used.
350
- */
351
- message: string;
352
-
353
- /**
354
- * The welcome notification's title. You can localize this to your own language. If not set, or left blank, the site's title will be used.
355
- * Set to one space ' ' to clear the title, although this is not recommended.
356
- */
357
- title?: string;
358
-
359
- /**
360
- * By default, clicking the welcome notification does not open any link.
361
- * This is recommended because the user has just visited your site and subscribed.
362
- */
363
- url: string;
364
- };
365
-
366
- /**
367
- * Will enable customization of the notify/subscription bell button.
368
- */
369
- notifyButton?: {
370
- /**
371
- * A function you define that returns true to show the Subscription Bell, or false to hide it.
372
- * Typically used the hide the Subscription Bell after the user is subscribed.
373
- * This function is not re-evaluated on every state change; this function is only evaluated once when the Subscription Bell begins to show.
374
- */
375
- displayPredicate?: () => boolean | Promise<boolean>;
376
-
377
- /**
378
- * Enable the Subscription Bell. The Subscription Bell is otherwise disabled by default.
379
- */
380
- enable?: boolean;
381
-
382
- /** Specify CSS-valid pixel offsets using bottom, left, and right. */
383
- offset?: { bottom: string; left: string; right: string };
384
-
385
- /**
386
- * If `true`, the Subscription Bell will display an icon that there is 1 unread message.
387
- * When hovering over the Subscription Bell, the user will see custom text set by message.prenotify.
388
- */
389
- prenotify: boolean;
390
-
391
- /** Either `bottom-left` or `bottom-right`. The Subscription Bell will be fixed at this location on your page. */
392
- position?: 'bottom-left' | 'bottom-right';
393
-
394
- /** Set `false` to hide the 'Powered by OneSignal' text in the Subscription Bell dialog popup. */
395
- showCredit: boolean;
396
-
397
- /**
398
- * The Subscription Bell will initially appear at one of these sizes, and then shrink down to size `small` after the user subscribes.
399
- */
400
- size?: 'small' | 'medium' | 'large';
401
-
402
- /** Customize the Subscription Bell text. */
403
- text: {
404
- 'dialog.blocked.message': string;
405
- 'dialog.blocked.title': string;
406
- 'dialog.main.button.subscribe': string;
407
- 'dialog.main.button.unsubscribe': string;
408
- 'dialog.main.title': string;
409
- 'message.action.resubscribed': string;
410
- 'message.action.subscribed': string;
411
- 'message.action.subscribing': string;
412
- 'message.action.unsubscribed': string;
413
- 'message.prenotify': string;
414
- 'tip.state.blocked': string;
415
- 'tip.state.subscribed': string;
416
- 'tip.state.unsubscribed': string;
417
- };
418
- };
419
-
420
- persistNotification?: boolean;
421
- webhooks?: {
422
- /**
423
- * Enable this setting only if your server has CORS enabled and supports non-simple CORS requests.
424
- * If this setting is disabled, your webhook will not need CORS to receive data, but it will not receive the custom headers.
425
- * The simplest option is to leave it disabled.
426
- * @default false
427
- */
428
- cors: boolean;
429
-
430
- /**
431
- * This event occurs after a notification is clicked.
432
- * @example https://site.com/hook
433
- */
434
- 'notification.clicked'?: string;
435
-
436
- /**
437
- * This event occurs after a notification is intentionally dismissed by the user (clicking the notification body or one of the notification action buttons does not trigger the dismissed webhook),
438
- * after a group of notifications are all dismissed (with this notification as part of that group), or after a notification expires on its own time and disappears. This event is supported on Chrome only.
439
- * @example https://site.com/hook
440
- */
441
- 'notification.dismissed'?: string;
442
-
443
- /**
444
- * This event occurs after a notification is displayed.
445
- * @example https://site.com/hook
446
- */
447
- 'notification.willDisplay'?: string;
448
- };
449
- autoResubscribe?: boolean;
450
- autoRegister?: boolean;
451
- notificationClickHandlerMatch?: string;
452
- notificationClickHandlerAction?: string;
453
- path?: string;
454
- serviceWorkerParam?: { scope: string };
455
- serviceWorkerPath?: string;
456
- serviceWorkerOverrideForTypical?: boolean;
457
- serviceWorkerUpdaterPath?: string;
458
- allowLocalhostAsSecureOrigin?: boolean;
459
- [key: string]: any;
460
- }
461
-
462
- export interface IOneSignalOneSignal {
463
- Slidedown: IOneSignalSlidedown;
464
- Notifications: IOneSignalNotifications;
465
- Session: IOneSignalSession;
466
- User: IOneSignalUser;
467
- Debug: IOneSignalDebug;
468
- login(externalId: string, jwtToken?: string): Promise<void>;
469
- logout(): Promise<void>;
470
- init(options: IInitObject): Promise<void>;
471
- setConsentGiven(consent: boolean): Promise<void>;
472
- setConsentRequired(requiresConsent: boolean): Promise<void>;
473
- }
474
- export interface IOneSignalNotifications {
475
- permissionNative: NotificationPermission;
476
- permission: boolean;
477
- setDefaultUrl(url: string): Promise<void>;
478
- setDefaultTitle(title: string): Promise<void>;
479
- isPushSupported(): boolean;
480
- requestPermission(): Promise<void>;
481
- addEventListener<K extends NotificationEventName>(event: K, listener: (obj: NotificationEventTypeMap[K]) => void): void;
482
- removeEventListener<K extends NotificationEventName>(event: K, listener: (obj: NotificationEventTypeMap[K]) => void): void;
483
- }
484
- export interface IOneSignalSlidedown {
485
- promptPush(options?: AutoPromptOptions): Promise<void>;
486
- promptPushCategories(options?: AutoPromptOptions): Promise<void>;
487
- promptSms(options?: AutoPromptOptions): Promise<void>;
488
- promptEmail(options?: AutoPromptOptions): Promise<void>;
489
- promptSmsAndEmail(options?: AutoPromptOptions): Promise<void>;
490
- addEventListener(event: SlidedownEventName, listener: (wasShown: boolean) => void): void;
491
- removeEventListener(event: SlidedownEventName, listener: (wasShown: boolean) => void): void;
492
- }
493
- export interface IOneSignalDebug {
494
- setLogLevel(logLevel: string): void;
495
- }
496
- export interface IOneSignalSession {
497
- sendOutcome(outcomeName: string, outcomeWeight?: number): Promise<void>;
498
- sendUniqueOutcome(outcomeName: string): Promise<void>;
499
- }
500
- export interface IOneSignalUser {
501
- onesignalId: string | undefined;
502
- externalId: string | undefined;
503
- PushSubscription: IOneSignalPushSubscription;
504
- addAlias(label: string, id: string): void;
505
- addAliases(aliases: { [key: string]: string }): void;
506
- removeAlias(label: string): void;
507
- removeAliases(labels: string[]): void;
508
- addEmail(email: string): void;
509
- removeEmail(email: string): void;
510
- addSms(smsNumber: string): void;
511
- removeSms(smsNumber: string): void;
512
- addTag(key: string, value: string): void;
513
- addTags(tags: { [key: string]: string }): void;
514
- removeTag(key: string): void;
515
- removeTags(keys: string[]): void;
516
- getTags(): { [key: string]: string };
517
- addEventListener(event: 'change', listener: (change: UserChangeEvent) => void): void;
518
- removeEventListener(event: 'change', listener: (change: UserChangeEvent) => void): void;
519
- setLanguage(language: string): void;
520
- getLanguage(): string;
521
- }
522
- export interface IOneSignalPushSubscription {
523
- id: string | null | undefined;
524
- token: string | null | undefined;
525
- optedIn: boolean | undefined;
526
- optIn(): Promise<void>;
527
- optOut(): Promise<void>;
528
- addEventListener(event: 'change', listener: (change: SubscriptionChangeEvent) => void): void;
529
- removeEventListener(event: 'change', listener: (change: SubscriptionChangeEvent) => void): void;
530
- }
531
- function oneSignalLogin(externalId: string, jwtToken?: string): Promise<void> {
532
- return new Promise(function (resolve, reject) {
533
- if (isOneSignalScriptFailed) {
534
- reject(new Error('OneSignal script failed to load.'));
535
- return;
536
- }
537
-
538
- try {
539
- window.OneSignalDeferred?.push((OneSignal) => {
540
- OneSignal.login(externalId, jwtToken).then(() => resolve())
541
- .catch(error => reject(error));
542
- });
543
- } catch (error) {
544
- reject(error);
545
- }
546
- });
547
- }
548
- function oneSignalLogout(): Promise<void> {
549
- return new Promise(function (resolve, reject) {
550
- if (isOneSignalScriptFailed) {
551
- reject(new Error('OneSignal script failed to load.'));
552
- return;
553
- }
554
-
555
- try {
556
- window.OneSignalDeferred?.push((OneSignal) => {
557
- OneSignal.logout().then(() => resolve())
558
- .catch(error => reject(error));
559
- });
560
- } catch (error) {
561
- reject(error);
562
- }
563
- });
564
- }
565
- function oneSignalSetConsentGiven(consent: boolean): Promise<void> {
566
- return new Promise(function (resolve, reject) {
567
- if (isOneSignalScriptFailed) {
568
- reject(new Error('OneSignal script failed to load.'));
569
- return;
570
- }
571
-
572
- try {
573
- window.OneSignalDeferred?.push((OneSignal) => {
574
- OneSignal.setConsentGiven(consent).then(() => resolve())
575
- .catch(error => reject(error));
576
- });
577
- } catch (error) {
578
- reject(error);
579
- }
580
- });
581
- }
582
- function oneSignalSetConsentRequired(requiresConsent: boolean): Promise<void> {
583
- return new Promise(function (resolve, reject) {
584
- if (isOneSignalScriptFailed) {
585
- reject(new Error('OneSignal script failed to load.'));
586
- return;
587
- }
588
-
589
- try {
590
- window.OneSignalDeferred?.push((OneSignal) => {
591
- OneSignal.setConsentRequired(requiresConsent).then(() => resolve())
592
- .catch(error => reject(error));
593
- });
594
- } catch (error) {
595
- reject(error);
596
- }
597
- });
598
- }
599
- function slidedownPromptPush(options?: AutoPromptOptions): Promise<void> {
600
- return new Promise(function (resolve, reject) {
601
- if (isOneSignalScriptFailed) {
602
- reject(new Error('OneSignal script failed to load.'));
603
- return;
604
- }
605
-
606
- try {
607
- window.OneSignalDeferred?.push((OneSignal) => {
608
- OneSignal.Slidedown.promptPush(options).then(() => resolve())
609
- .catch(error => reject(error));
610
- });
611
- } catch (error) {
612
- reject(error);
613
- }
614
- });
615
- }
616
- function slidedownPromptPushCategories(options?: AutoPromptOptions): Promise<void> {
617
- return new Promise(function (resolve, reject) {
618
- if (isOneSignalScriptFailed) {
619
- reject(new Error('OneSignal script failed to load.'));
620
- return;
621
- }
622
-
623
- try {
624
- window.OneSignalDeferred?.push((OneSignal) => {
625
- OneSignal.Slidedown.promptPushCategories(options).then(() => resolve())
626
- .catch(error => reject(error));
627
- });
628
- } catch (error) {
629
- reject(error);
630
- }
631
- });
632
- }
633
- function slidedownPromptSms(options?: AutoPromptOptions): Promise<void> {
634
- return new Promise(function (resolve, reject) {
635
- if (isOneSignalScriptFailed) {
636
- reject(new Error('OneSignal script failed to load.'));
637
- return;
638
- }
639
-
640
- try {
641
- window.OneSignalDeferred?.push((OneSignal) => {
642
- OneSignal.Slidedown.promptSms(options).then(() => resolve())
643
- .catch(error => reject(error));
644
- });
645
- } catch (error) {
646
- reject(error);
647
- }
648
- });
649
- }
650
- function slidedownPromptEmail(options?: AutoPromptOptions): Promise<void> {
651
- return new Promise(function (resolve, reject) {
652
- if (isOneSignalScriptFailed) {
653
- reject(new Error('OneSignal script failed to load.'));
654
- return;
655
- }
656
-
657
- try {
658
- window.OneSignalDeferred?.push((OneSignal) => {
659
- OneSignal.Slidedown.promptEmail(options).then(() => resolve())
660
- .catch(error => reject(error));
661
- });
662
- } catch (error) {
663
- reject(error);
664
- }
665
- });
666
- }
667
- function slidedownPromptSmsAndEmail(options?: AutoPromptOptions): Promise<void> {
668
- return new Promise(function (resolve, reject) {
669
- if (isOneSignalScriptFailed) {
670
- reject(new Error('OneSignal script failed to load.'));
671
- return;
672
- }
673
-
674
- try {
675
- window.OneSignalDeferred?.push((OneSignal) => {
676
- OneSignal.Slidedown.promptSmsAndEmail(options).then(() => resolve())
677
- .catch(error => reject(error));
678
- });
679
- } catch (error) {
680
- reject(error);
681
- }
682
- });
683
- }
684
- function slidedownAddEventListener(event: SlidedownEventName, listener: (wasShown: boolean) => void): void {
685
-
686
- window.OneSignalDeferred?.push((OneSignal) => {
687
- OneSignal.Slidedown.addEventListener(event, listener);
688
- });
689
-
690
- }
691
- function slidedownRemoveEventListener(event: SlidedownEventName, listener: (wasShown: boolean) => void): void {
692
-
693
- window.OneSignalDeferred?.push((OneSignal) => {
694
- OneSignal.Slidedown.removeEventListener(event, listener);
695
- });
696
-
697
- }
698
- function notificationsSetDefaultUrl(url: string): Promise<void> {
699
- return new Promise(function (resolve, reject) {
700
- if (isOneSignalScriptFailed) {
701
- reject(new Error('OneSignal script failed to load.'));
702
- return;
703
- }
704
-
705
- try {
706
- window.OneSignalDeferred?.push((OneSignal) => {
707
- OneSignal.Notifications.setDefaultUrl(url).then(() => resolve())
708
- .catch(error => reject(error));
709
- });
710
- } catch (error) {
711
- reject(error);
712
- }
713
- });
714
- }
715
- function notificationsSetDefaultTitle(title: string): Promise<void> {
716
- return new Promise(function (resolve, reject) {
717
- if (isOneSignalScriptFailed) {
718
- reject(new Error('OneSignal script failed to load.'));
719
- return;
720
- }
721
-
722
- try {
723
- window.OneSignalDeferred?.push((OneSignal) => {
724
- OneSignal.Notifications.setDefaultTitle(title).then(() => resolve())
725
- .catch(error => reject(error));
726
- });
727
- } catch (error) {
728
- reject(error);
729
- }
730
- });
731
- }
732
- function notificationsRequestPermission(): Promise<void> {
733
- return new Promise(function (resolve, reject) {
734
- if (isOneSignalScriptFailed) {
735
- reject(new Error('OneSignal script failed to load.'));
736
- return;
737
- }
738
-
739
- try {
740
- window.OneSignalDeferred?.push((OneSignal) => {
741
- OneSignal.Notifications.requestPermission().then(() => resolve())
742
- .catch(error => reject(error));
743
- });
744
- } catch (error) {
745
- reject(error);
746
- }
747
- });
748
- }
749
- function notificationsAddEventListener<K extends NotificationEventName>(event: K, listener: (obj: NotificationEventTypeMap[K]) => void): void {
750
-
751
- window.OneSignalDeferred?.push((OneSignal) => {
752
- OneSignal.Notifications.addEventListener(event, listener);
753
- });
754
-
755
- }
756
- function notificationsRemoveEventListener<K extends NotificationEventName>(event: K, listener: (obj: NotificationEventTypeMap[K]) => void): void {
757
-
758
- window.OneSignalDeferred?.push((OneSignal) => {
759
- OneSignal.Notifications.removeEventListener(event, listener);
760
- });
761
-
762
- }
763
- function sessionSendOutcome(outcomeName: string, outcomeWeight?: number): Promise<void> {
764
- return new Promise(function (resolve, reject) {
765
- if (isOneSignalScriptFailed) {
766
- reject(new Error('OneSignal script failed to load.'));
767
- return;
768
- }
769
-
770
- try {
771
- window.OneSignalDeferred?.push((OneSignal) => {
772
- OneSignal.Session.sendOutcome(outcomeName, outcomeWeight).then(() => resolve())
773
- .catch(error => reject(error));
774
- });
775
- } catch (error) {
776
- reject(error);
777
- }
778
- });
779
- }
780
- function sessionSendUniqueOutcome(outcomeName: string): Promise<void> {
781
- return new Promise(function (resolve, reject) {
782
- if (isOneSignalScriptFailed) {
783
- reject(new Error('OneSignal script failed to load.'));
784
- return;
785
- }
786
-
787
- try {
788
- window.OneSignalDeferred?.push((OneSignal) => {
789
- OneSignal.Session.sendUniqueOutcome(outcomeName).then(() => resolve())
790
- .catch(error => reject(error));
791
- });
792
- } catch (error) {
793
- reject(error);
794
- }
795
- });
796
- }
797
- function userAddAlias(label: string, id: string): void {
798
-
799
- window.OneSignalDeferred?.push((OneSignal) => {
800
- OneSignal.User.addAlias(label, id);
801
- });
802
-
803
- }
804
- function userAddAliases(aliases: { [key: string]: string }): void {
805
-
806
- window.OneSignalDeferred?.push((OneSignal) => {
807
- OneSignal.User.addAliases(aliases);
808
- });
809
-
810
- }
811
- function userRemoveAlias(label: string): void {
812
-
813
- window.OneSignalDeferred?.push((OneSignal) => {
814
- OneSignal.User.removeAlias(label);
815
- });
816
-
817
- }
818
- function userRemoveAliases(labels: string[]): void {
819
-
820
- window.OneSignalDeferred?.push((OneSignal) => {
821
- OneSignal.User.removeAliases(labels);
822
- });
823
-
824
- }
825
- function userAddEmail(email: string): void {
826
-
827
- window.OneSignalDeferred?.push((OneSignal) => {
828
- OneSignal.User.addEmail(email);
829
- });
830
-
831
- }
832
- function userRemoveEmail(email: string): void {
833
-
834
- window.OneSignalDeferred?.push((OneSignal) => {
835
- OneSignal.User.removeEmail(email);
836
- });
837
-
838
- }
839
- function userAddSms(smsNumber: string): void {
840
-
841
- window.OneSignalDeferred?.push((OneSignal) => {
842
- OneSignal.User.addSms(smsNumber);
843
- });
844
-
845
- }
846
- function userRemoveSms(smsNumber: string): void {
847
-
848
- window.OneSignalDeferred?.push((OneSignal) => {
849
- OneSignal.User.removeSms(smsNumber);
850
- });
851
-
852
- }
853
- function userAddTag(key: string, value: string): void {
854
-
855
- window.OneSignalDeferred?.push((OneSignal) => {
856
- OneSignal.User.addTag(key, value);
857
- });
858
-
859
- }
860
- function userAddTags(tags: { [key: string]: string }): void {
861
-
862
- window.OneSignalDeferred?.push((OneSignal) => {
863
- OneSignal.User.addTags(tags);
864
- });
865
-
866
- }
867
- function userRemoveTag(key: string): void {
868
-
869
- window.OneSignalDeferred?.push((OneSignal) => {
870
- OneSignal.User.removeTag(key);
871
- });
872
-
873
- }
874
- function userRemoveTags(keys: string[]): void {
875
-
876
- window.OneSignalDeferred?.push((OneSignal) => {
877
- OneSignal.User.removeTags(keys);
878
- });
879
-
880
- }
881
- function userGetTags(): { [key: string]: string } {
882
- let retVal: { [key: string]: string };
883
- window.OneSignalDeferred?.push((OneSignal) => {
884
- retVal = OneSignal.User.getTags();
885
- });
886
- return retVal;
887
- }
888
- function userAddEventListener(event: 'change', listener: (change: UserChangeEvent) => void): void {
889
-
890
- window.OneSignalDeferred?.push((OneSignal) => {
891
- OneSignal.User.addEventListener(event, listener);
892
- });
893
-
894
- }
895
- function userRemoveEventListener(event: 'change', listener: (change: UserChangeEvent) => void): void {
896
-
897
- window.OneSignalDeferred?.push((OneSignal) => {
898
- OneSignal.User.removeEventListener(event, listener);
899
- });
900
-
901
- }
902
- function userSetLanguage(language: string): void {
903
-
904
- window.OneSignalDeferred?.push((OneSignal) => {
905
- OneSignal.User.setLanguage(language);
906
- });
907
-
908
- }
909
- function userGetLanguage(): string {
910
- let retVal: string;
911
- window.OneSignalDeferred?.push((OneSignal) => {
912
- retVal = OneSignal.User.getLanguage();
913
- });
914
- return retVal;
915
- }
916
- function pushSubscriptionOptIn(): Promise<void> {
917
- return new Promise(function (resolve, reject) {
918
- if (isOneSignalScriptFailed) {
919
- reject(new Error('OneSignal script failed to load.'));
920
- return;
921
- }
922
-
923
- try {
924
- window.OneSignalDeferred?.push((OneSignal) => {
925
- OneSignal.User.PushSubscription.optIn().then(() => resolve())
926
- .catch(error => reject(error));
927
- });
928
- } catch (error) {
929
- reject(error);
930
- }
931
- });
932
- }
933
- function pushSubscriptionOptOut(): Promise<void> {
934
- return new Promise(function (resolve, reject) {
935
- if (isOneSignalScriptFailed) {
936
- reject(new Error('OneSignal script failed to load.'));
937
- return;
938
- }
939
-
940
- try {
941
- window.OneSignalDeferred?.push((OneSignal) => {
942
- OneSignal.User.PushSubscription.optOut().then(() => resolve())
943
- .catch(error => reject(error));
944
- });
945
- } catch (error) {
946
- reject(error);
947
- }
948
- });
949
- }
950
- function pushSubscriptionAddEventListener(event: 'change', listener: (change: SubscriptionChangeEvent) => void): void {
951
-
952
- window.OneSignalDeferred?.push((OneSignal) => {
953
- OneSignal.User.PushSubscription.addEventListener(event, listener);
954
- });
955
-
956
- }
957
- function pushSubscriptionRemoveEventListener(event: 'change', listener: (change: SubscriptionChangeEvent) => void): void {
958
-
959
- window.OneSignalDeferred?.push((OneSignal) => {
960
- OneSignal.User.PushSubscription.removeEventListener(event, listener);
961
- });
962
-
963
- }
964
- function debugSetLogLevel(logLevel: string): void {
965
-
966
- window.OneSignalDeferred?.push((OneSignal) => {
967
- OneSignal.Debug.setLogLevel(logLevel);
968
- });
969
-
970
- }
971
- const PushSubscriptionNamespace: IOneSignalPushSubscription = {
972
- get id(): string | null | undefined { return window.OneSignal?.User?.PushSubscription?.id; },
973
- get token(): string | null | undefined { return window.OneSignal?.User?.PushSubscription?.token; },
974
- get optedIn(): boolean | undefined { return window.OneSignal?.User?.PushSubscription?.optedIn; },
975
- optIn: pushSubscriptionOptIn,
976
- optOut: pushSubscriptionOptOut,
977
- addEventListener: pushSubscriptionAddEventListener,
978
- removeEventListener: pushSubscriptionRemoveEventListener,
979
- };
980
-
981
- const UserNamespace: IOneSignalUser = {
982
- get onesignalId(): string | undefined { return window.OneSignal?.User?.onesignalId; },
983
- get externalId(): string | undefined { return window.OneSignal?.User?.externalId; },
984
- addAlias: userAddAlias,
985
- addAliases: userAddAliases,
986
- removeAlias: userRemoveAlias,
987
- removeAliases: userRemoveAliases,
988
- addEmail: userAddEmail,
989
- removeEmail: userRemoveEmail,
990
- addSms: userAddSms,
991
- removeSms: userRemoveSms,
992
- addTag: userAddTag,
993
- addTags: userAddTags,
994
- removeTag: userRemoveTag,
995
- removeTags: userRemoveTags,
996
- getTags: userGetTags,
997
- addEventListener: userAddEventListener,
998
- removeEventListener: userRemoveEventListener,
999
- setLanguage: userSetLanguage,
1000
- getLanguage: userGetLanguage,
1001
- PushSubscription: PushSubscriptionNamespace,
1002
- };
1003
-
1004
- const SessionNamespace: IOneSignalSession = {
1005
- sendOutcome: sessionSendOutcome,
1006
- sendUniqueOutcome: sessionSendUniqueOutcome,
1007
- };
1008
-
1009
- const DebugNamespace: IOneSignalDebug = {
1010
- setLogLevel: debugSetLogLevel,
1011
- };
1012
-
1013
- const SlidedownNamespace: IOneSignalSlidedown = {
1014
- promptPush: slidedownPromptPush,
1015
- promptPushCategories: slidedownPromptPushCategories,
1016
- promptSms: slidedownPromptSms,
1017
- promptEmail: slidedownPromptEmail,
1018
- promptSmsAndEmail: slidedownPromptSmsAndEmail,
1019
- addEventListener: slidedownAddEventListener,
1020
- removeEventListener: slidedownRemoveEventListener,
1021
- };
1022
-
1023
- const NotificationsNamespace: IOneSignalNotifications = {
1024
- get permissionNative(): NotificationPermission { return window.OneSignal?.Notifications?.permissionNative ?? 'default'; },
1025
- get permission(): boolean { return window.OneSignal?.Notifications?.permission ?? false; },
1026
- setDefaultUrl: notificationsSetDefaultUrl,
1027
- setDefaultTitle: notificationsSetDefaultTitle,
1028
- isPushSupported,
1029
- requestPermission: notificationsRequestPermission,
1030
- addEventListener: notificationsAddEventListener,
1031
- removeEventListener: notificationsRemoveEventListener,
1032
- };
1033
-
1034
- const OneSignalNamespace: IOneSignalOneSignal = {
1035
- login: oneSignalLogin,
1036
- logout: oneSignalLogout,
1037
- init,
1038
- setConsentGiven: oneSignalSetConsentGiven,
1039
- setConsentRequired: oneSignalSetConsentRequired,
1040
- Slidedown: SlidedownNamespace,
1041
- Notifications: NotificationsNamespace,
1042
- Session: SessionNamespace,
1043
- User: UserNamespace,
1044
- Debug: DebugNamespace,
1045
- };
1046
-
1047
- const OneSignalVuePlugin = {
1048
- install(app: typeof VueApp) {
1049
- app.prototype.$OneSignal = OneSignalNamespace as IOneSignalOneSignal;
1050
- }
1051
- }
1052
-
1053
- export default OneSignalVuePlugin;