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