OneSignal với Nextjs 14 website
-
Cài đặt gói
yarn add react-onesignal
với version 3.0.1 -
Mở quyền thông báo
- 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
- xem thêm hướng dẫn ở đây : https://documentation.onesignal.com/docs/notifications-not-shown-web-push
- Code OneSignal
- kiểm tra cấp quyền chưa, chưa cấp thì mình enable init, có rồi thì thôi
- login tự mình cấp , nó có thêm tham số thứ 2 là token , có sài thì thêm vô, hông thì thôi , thêm vô thì nó ghi nhận lại trong Audience - Subscriptions trên dashboard.onesignal.com
await OneSignal.login('huyi_abi');
await OneSignal.User.addAlias('myAlias', 'huyi');
'use client';
import {
PropsWithChildren,
createContext,
useContext,
useEffect,
useState,
} from 'react';
import OneSignal from 'react-onesignal';
const useLogic = () => {
const appId = '9dcb4b67-6e24-4eb5-9be6-a8e19b71f63d'; // muốn có cái này thì đăng ký app là có
const [enable, setEnable] = useState(false);
useEffect(() => {
const init = async () => {
try {
if (!enable) {
await OneSignal.init({
appId,
notifyButton: {
enable: true,
},
autoResubscribe: true, // tự động theo đõi
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'); // này để log, hông muốn log thì để ""
} catch (error) {
console.log('error :>> ', error);
}
};
init();
}, [enable]);
return {};
};
type Extra = {};
type ValueCtx = ReturnType<typeof useLogic> & Extra;
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);
mình tạo cái OneSignalSDKWorker trong public : /public/OneSignalSDKWorker.js
importScripts('https://onesignal.com/sdks/web/v16/OneSignalSDK.sw.js');
- hướng dẫn đăng ký App
Cái này quan trọng :
Mình sài package nên khỏi dùng cái này
Chạy không ra thông báo thì cmt ở dưới nha!
All rights reserved
Bình luận
👍️👍️ bài hay mà trình bày còn đẹp. Gút Gút
thanh em
de thuong qó
quá bổ ích, cảm ơn anh!!
thanh em
May quá đúng thứ mình đang tìm, thanks bạn vì bài viết bổ ích này nhé👍️