Cài Đặt OneSignal cho Website Next.js 14
1. Cài Đặt Gói OneSignal
Để bắt đầu tích hợp OneSignal vào dự án Next.js 14, bạn cần cài đặt gói react-onesignal
. Sử dụng lệnh sau để cài đặt:
bash
yarn add react-onesignal@3.0.1
2. Mở Quyền Thông Báo
Trước khi sử dụng thông báo đẩy, bạn cần đảm bảo rằng quyền thông báo đã được mở cho ứng dụng. Thực hiện các bước sau:
- Mở quyền cho ứng dụng trong Cài Đặt của máy tính.
- Cấp quyền thông báo cho website của bạn.
- Để biết thêm chi tiết, hãy xem hướng dẫn tại OneSignal Documentation.
3. Cấu Hình OneSignal
Để cấu hình OneSignal, bạn cần thực hiện các bước sau:
- Kiểm tra quyền đã được cấp chưa; nếu chưa, hãy khởi tạo.
- Đối với thông tin đăng nhập, bạn cần tham số token; nếu có, hãy thêm vào để theo dõi.
- Các lệnh cần thiết:
javascript
await OneSignal.login('huyi_abi');
await OneSignal.User.addAlias('myAlias', 'huyi');
4. Triển Khai OneSignal Trong Dự Án
Để tích hợp OneSignal vào dự án của bạn, dưới đây là mã nguồn mẫu:
javascript
'use client';
import {
PropsWithChildren,
createContext,
useContext,
useEffect,
useState,
} from 'react';
import OneSignal from 'react-onesignal';
const useLogic = () => {
const appId = '9dcb4b67-6e24-4eb5-9be6-a8e19b71f63d'; // Đăng ký app để có appId
const [enable, setEnable] = useState(false);
useEffect(() => {
const init = async () => {
try {
if (!enable) {
await OneSignal.init({
appId,
notifyButton: {
enable: true,
},
autoResubscribe: true,
autoRegister: true,
serviceWorkerPath: '/OneSignalSDKWorker.js',
allowLocalhostAsSecureOrigin: true,
});
}
setEnable(OneSignal.Notifications.permission);
await OneSignal.Notifications.requestPermission();
await OneSignal.Slidedown.promptPush();
await OneSignal.login('huyi_abi');
await OneSignal.User.addAlias('myAlias', 'huyi');
await OneSignal.Debug.setLogLevel('trace');
} catch (error) {
console.log('error :>> ', error);
}
};
init();
}, [enable]);
return {};
};
export const AppCtx = createContext({} as ValueCtx);
export const AppProvider = ({ ...props }: PropsWithChildren<Extra>) => {
const valueCtx = useLogic();
return (
<AppCtx.Provider value={{ ...valueCtx, ...props }}>
<>{props.children}</>
</AppCtx.Provider>
);
};
export const useAppCtx = () => useContext(AppCtx);
5. Tạo Tập Tin OneSignalSDKWorker
Bạn cần tạo tập tin OneSignalSDKWorker.js
trong thư mục public
:
javascript
importScripts('https://onesignal.com/sdks/web/v16/OneSignalSDK.sw.js');
6. Hướng Dẫn Đăng Ký App
Chú ý rằng việc đăng ký App là rất quan trọng, tuy nhiên do sử dụng package, bạn có thể bỏ qua bước này. Nếu bạn gặp vấn đề với thông báo không hiển thị, hãy để lại bình luận bên dưới để được giúp đỡ!
source: viblo