Skip to content

Commit 24b3ece

Browse files
author
Rodrigo Gomez Palacio
authored
Merge pull request #1183 from OneSignal/send-self-local-2
Change the sendSelfNotification method to use local push functionality
2 parents 30bf21e + 49f8f7f commit 24b3ece

File tree

6 files changed

+65
-47
lines changed

6 files changed

+65
-47
lines changed

express_webpack/index.html

+12
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,17 @@
154154
})
155155
}
156156

157+
function sendSelfNotification() {
158+
OneSignal.push(function() {
159+
OneSignal.sendSelfNotification('Title', 'message', `https://localhost:4001/?app_id=${appId}`, 'https://t3.ftcdn.net/jpg/03/08/73/34/360_F_308733458_QBzwMVu8ZzdGEp9Wwq1fAYaDgtP3UVwl.jpg', { test: 'foo' }, [{
160+
id: 'like-button',
161+
text: 'Like',
162+
icon: 'https://image.similarpng.com/very-thumbnail/2020/06/Icon-like-button-transparent-PNG.png',
163+
url: 'https://onesignal.com'
164+
}]);
165+
});
166+
}
167+
157168
</script>
158169
<head>
159170
<meta charset="utf-8">
@@ -189,6 +200,7 @@ <h1>OneSignal WebSDK Sandbox</h1>
189200
<button onclick="javascript:showSmsSlidedown();">Show Sms Slidedown</button>
190201
<button onclick="javascript:showEmailSlidedown();">Show Email Slidedown</button>
191202
<button onclick="javascript:showSmsAndEmailSlidedown();">Show Sms & Email Slidedown</button>
203+
<button onclick="javascript:sendSelfNotification();">Send Self Notification</button>
192204
<br />
193205
<br />
194206
<div class='onesignal-customlink-container'></div>

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
"jest": "jest --coverage"
4141
},
4242
"config": {
43-
"sdkVersion": "151605"
43+
"sdkVersion": "151606"
4444
},
4545
"repository": {
4646
"type": "git",

src/OneSignal.ts

+48-10
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
awaitOneSignalInitAndSupported,
3737
executeCallback,
3838
getConsoleStyle,
39+
getPlatformNotificationIcon,
3940
isValidEmail,
4041
logMethodCall,
4142
} from './utils';
@@ -713,16 +714,16 @@ export default class OneSignal {
713714
/**
714715
* @PublicApi
715716
*/
716-
static async sendSelfNotification(title: string = 'OneSignal Test Message',
717-
message: string = 'This is an example notification.',
718-
url: string = `${new URL(location.href).origin}?_osp=do_not_open`,
719-
icon: URL,
720-
data: Map<String, any>,
721-
buttons: Array<NotificationActionButton>): Promise<void> {
717+
static async sendSelfNotification(title = 'OneSignal Test Message',
718+
message = 'This is an example notification.',
719+
url = `${new URL(location.href).origin}?_osp=do_not_open`,
720+
icon?: string,
721+
data?: Record<string, any>,
722+
buttons?: Array<any>): Promise<void> {
722723
await awaitOneSignalInitAndSupported();
723724
logMethodCall('sendSelfNotification', title, message, url, icon, data, buttons);
724725
const appConfig = await Database.getAppConfig();
725-
const subscription = await Database.getSubscription();
726+
726727
if (!appConfig.appId)
727728
throw new InvalidStateError(InvalidStateReason.MissingAppId);
728729
if (!(await OneSignal.isPushNotificationsEnabled()))
@@ -731,11 +732,48 @@ export default class OneSignal {
731732
throw new InvalidArgumentError('url', InvalidArgumentReason.Malformed);
732733
if (!ValidatorUtils.isValidUrl(icon, { allowEmpty: true, requireHttps: true }))
733734
throw new InvalidArgumentError('icon', InvalidArgumentReason.Malformed);
735+
if (!icon) {
736+
// get default icon
737+
const icons = await MainHelper.getNotificationIcons();
738+
icon = getPlatformNotificationIcon(icons);
739+
}
740+
741+
const convertButtonsToNotificationActionType = (buttons: Array<any>) => {
742+
const convertedButtons = [];
734743

735-
if (subscription.deviceId) {
736-
await OneSignalApi.sendNotification(appConfig.appId, [subscription.deviceId], { en : title }, { en : message },
737-
url, icon, data, buttons);
744+
for (let i=0; i<buttons.length; i++) {
745+
const button = buttons[i];
746+
convertedButtons.push({
747+
action: button.id,
748+
title: button.text,
749+
icon: button.icon,
750+
url: button.url
751+
});
752+
}
753+
754+
return convertedButtons;
755+
};
756+
757+
const dataPayload = {
758+
data,
759+
url,
760+
buttons: buttons ? convertButtonsToNotificationActionType(buttons) : undefined
738761
}
762+
763+
this.context.serviceWorkerManager.getRegistration().then(async (registration) => {
764+
if (!registration) {
765+
Log.error("Service worker registration not available.");
766+
return;
767+
}
768+
769+
const options = {
770+
body: message,
771+
data: dataPayload,
772+
icon: icon,
773+
actions: buttons ? convertButtonsToNotificationActionType(buttons) : [],
774+
};
775+
registration.showNotification(title, options);
776+
});
739777
}
740778

741779
/**

src/OneSignalApi.ts

-4
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,6 @@ export default class OneSignalApi {
1717
return OneSignalApiShared.updatePlayer(appId, playerId, options);
1818
}
1919

20-
static sendNotification(appId: string, playerIds: Array<string>, titles, contents, url, icon, data, buttons) {
21-
return OneSignalApiShared.sendNotification(appId, playerIds, titles, contents, url, icon, data, buttons);
22-
}
23-
2420
static jsonpLib(url: string, fn: Function) {
2521
JSONP(url, null, fn);
2622
}

src/OneSignalApiShared.ts

-23
Original file line numberDiff line numberDiff line change
@@ -21,29 +21,6 @@ export default class OneSignalApiShared {
2121
return OneSignalApiBase.put(`players/${playerId}`, { app_id: appId, ...options });
2222
}
2323

24-
static sendNotification(appId: string, playerIds: Array<string>, titles, contents, url, icon, data, buttons) {
25-
var params = {
26-
app_id: appId,
27-
contents: contents,
28-
include_player_ids: playerIds,
29-
isAnyWeb: true,
30-
data: data,
31-
web_buttons: buttons
32-
};
33-
if (titles) {
34-
(params as any).headings = titles;
35-
}
36-
if (url) {
37-
(params as any).url = url;
38-
}
39-
if (icon) {
40-
(params as any).chrome_web_icon = icon;
41-
(params as any).firefox_icon = icon;
42-
}
43-
Utils.trimUndefined(params);
44-
return OneSignalApiBase.post('notifications', params);
45-
}
46-
4724
static async createUser(deviceRecord: DeviceRecord): Promise<string | null> {
4825
const serializedDeviceRecord = deviceRecord.serialize();
4926
Utils.enforceAppId(serializedDeviceRecord.app_id);

src/helpers/EventHelper.ts

+4-9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import Event from '../Event';
22
import LimitStore from '../LimitStore';
3-
import OneSignalApiShared from '../OneSignalApiShared';
43
import Database from '../services/Database';
54
import { ContextSWInterface } from "../models/ContextSW";
65
import Log from '../libraries/Log';
@@ -84,8 +83,6 @@ export default class EventHelper {
8483
}
8584
EventHelper.sendingOrSentWelcomeNotification = true;
8685

87-
const { deviceId } = await Database.getSubscription();
88-
const { appId } = await Database.getAppConfig();
8986
let title =
9087
welcome_notification_opts !== undefined &&
9188
welcome_notification_opts['title'] !== undefined &&
@@ -108,13 +105,11 @@ export default class EventHelper {
108105
message = BrowserUtils.decodeHtmlEntities(message);
109106

110107
Log.debug('Sending welcome notification.');
111-
OneSignalApiShared.sendNotification(
112-
appId,
113-
[deviceId],
114-
{ en: title },
115-
{ en: message },
108+
OneSignal.sendSelfNotification(
109+
title,
110+
message,
116111
url,
117-
null,
112+
undefined,
118113
{ __isOneSignalWelcomeNotification: true },
119114
undefined
120115
);

0 commit comments

Comments
 (0)