웹 푸시 SDK 3.0
Pushwoosh 웹 푸시 SDK를 다운로드하고 압축을 풉니다. 다음 파일이 있어야 합니다:
Anchor link to- pushwoosh-service-worker.js
이 모든 파일을 웹사이트 디렉토리의 최상위 루트에 배치합니다.
Anchor link toSDK 초기화:
Anchor link to- CDN에서 SDK를 비동기적으로 포함합니다.
<script type="text/javascript" src="//cdn.pushwoosh.com/webpush/v3/pushwoosh-web-notifications.js" async></script>- 웹 푸시 SDK를 초기화하고 SDK가 완전히 로드될 때까지 초기화를 큐에 넣어야 합니다.
<script type="text/javascript">var Pushwoosh = Pushwoosh || [];Pushwoosh.push(['init', { logLevel: 'info', // 가능한 값: error, info, debug applicationCode: 'XXXXX-XXXXX', // Pushwoosh 제어판의 애플리케이션 코드 apiToken: 'XXXXXXX', // Device API 토큰 safariWebsitePushID: 'web.com.example.domain', // Apple 개발자 포털에서 얻은 고유한 역도메인 문자열. Safari 브라우저에 푸시 알림을 보낼 경우에만 필요합니다. defaultNotificationTitle: 'Pushwoosh', // 푸시 알림의 기본 제목을 설정합니다. defaultNotificationImage: 'https://yoursite.com/img/logo-medium.png', // 사용자 지정 알림 이미지의 URL autoSubscribe: false, // 또는 true. true인 경우 SDK 초기화 시 사용자에게 푸시 구독을 요청합니다. subscribeWidget: { enable: true }, userId: 'user_id', // 선택 사항, 사용자 지정 사용자 ID 설정 tags: { 'Name': 'John Smith' // 선택 사항, 사용자 지정 태그 설정 }}]);</script>웹 팝업
Anchor link toinit 객체에 webPopups를 추가하여 사이트에서 웹 팝업 캠페인을 활성화합니다.
webPopups: { enable: true, autoShow: true, // 선택 사항, 팝업을 자동으로 표시하지 않고 로드하려면 false로 설정 — 아래 WebPopups 메서드 참조},웹 팝업 캠페인은 프로모션, 공지 또는 리드 캡처 양식과 같이 제어판에서 구성하는 오버레이를 표시합니다. 웹 푸시 옵트인만 처리하는 사용자 지정 구독 팝업(subscribePopup)과 달리, 웹 팝업 캠페인은 구성한 모든 콘텐츠를 표시할 수 있습니다.
제어판에서의 설정은 웹 팝업 이해하기를 참조하십시오.
프로그래밍 방식 제어는 WebPopups 메서드 및 웹 팝업 이벤트를 참조하십시오.
푸시 구독 버튼
Anchor link to사용자에게 푸시 알림 구독을 유도하려면 웹사이트에 푸시 구독 버튼을 구현하는 것이 좋습니다. 사용자 경험을 향상시키고 더 많은 구독자를 확보하세요!
웹사이트에 푸시 알림 구현을 완료하려면 단계별 가이드에 따라 Pushwoosh 제어판에서 웹 플랫폼을 구성해야 합니다:
다른 범위에 서비스 워커 등록하기
Anchor link to때로는 서비스 워커 파일을 웹사이트의 루트 디렉토리가 아닌 하위 디렉토리에 배치해야 할 수도 있습니다.
이 경우, serviceWorkerUrl: “/push-notifications/pushwoosh-service-worker.js” 매개변수를 추가하여 구성(4.3단계)을 수정하십시오.
여기서 /push-notifications/pushwoosh-service-worker.js는 pushwoosh-service-worker.js 파일의 경로입니다.
이벤트 핸들러
Anchor link toPushwoosh 웹 SDK 3.0에서는 특정 이벤트를 구독하여 추적하거나, 더 이상 추적이 필요하지 않은 경우 이벤트 구독을 취소할 수 있습니다.
웹 SDK 3.0 로드를 추적하려면 다음과 같이 onLoad 이벤트를 발생시킵니다:
// Load EventPushwoosh.push(['onLoad', (api) => { console.log('Pushwoosh load!');}]);올바른 웹 SDK 초기화를 추적하려면 onReady 이벤트를 발생시킵니다:
// Ready EventPushwoosh.push((api) => { console.log('Pushwoosh ready!');});SDK 이벤트 중 하나를 구독하거나 구독 취소하려면 SDK 로드 후 핸들러를 사용하십시오:
Pushwoosh.push(['onLoad', (api) => { function onEventNameHandler() { console.log('Triggered event: event-name!'); }
// To subscribe to an event: Pushwoosh.addEventHandler('event-name', onEventNameHandler)
// To unsubscribe from an event: Pushwoosh.removeEventHandler('event-name', onEventNameHandler)}]);SDK 이벤트
Anchor link to구독 이벤트
Anchor link to사용자가 푸시 알림 수신에 동의한 후 실행됩니다.
Pushwoosh.push(['onLoad', (api) => { Pushwoosh.addEventHandler('subscribe', (payload) => { console.log('Triggered event: subscribe'); });}]);구독 취소 이벤트
Anchor link to기기가 알림에서 등록 해제된 후 실행됩니다.
Pushwoosh.push(['onLoad', (api) => { Pushwoosh.addEventHandler('unsubscribe', (payload) => { console.log('Triggered event: unsubscribe'); });}]);구독 위젯 이벤트
Anchor link to구독 프롬프트 위젯의 표시를 추적합니다.
Pushwoosh.push(['onLoad', (api) => { // Executed on displaying of the Subscription Prompt widget Pushwoosh.addEventHandler('show-subscription-widget', (payload) => { console.log('Triggered event: show-subscription-widget'); });
// Executed on hiding of the Subscription Prompt widget Pushwoosh.addEventHandler('hide-subscription-widget', (payload) => { console.log('Triggered event: hide-subscription-widget'); });}]);알림 권한 대화상자 이벤트
Anchor link to네이티브 구독 대화상자의 표시를 추적합니다.
Pushwoosh.push(['onLoad', function (api) { // Executed on permission dialog displaying Pushwoosh.addEventHandler('show-notification-permission-dialog', (payload) => { console.log('Triggered event: show-notification-permission-dialog'); });
// Executed on hiding the permission dialog with one of three possible statuses: // 1. default - the dialog is closed // 2. granted - permission is granted // 3. denied - permission is denied Pushwoosh.addEventHandler('hide-notification-permission-dialog', (payload) => { console.log('Triggered event: hide-notification-permission-dialog', payload.permission); });}]);권한 이벤트
Anchor link toSDK 초기화 시 푸시 알림 권한 상태를 확인하고, 이 상태가 변경될 때마다 업데이트를 추적합니다.
Pushwoosh.push(['onLoad', (api) => { // Executed during the SDK initialization if 'autoSubscribe: false' or/and if a user ignores a push notification prompt. Pushwoosh.addEventHandler('permission-default', (payload) => { console.log('Triggered event: permission-default'); });
// Executed during the SDK initialization if notifications are blocked or once a user blocks push notifications. Pushwoosh.addEventHandler('permission-denied', (payload) => { console.log('Triggered event: permission-denied'); });
// Executed during the SDK initialization if notifications are allowed or once a user allows push notifications. Pushwoosh.addEventHandler('permission-granted', (payload) => { console.log('Triggered event: permission-granted'); });}]);푸시 수신 이벤트
Anchor link to기기로의 푸시 전달을 추적합니다.
Pushwoosh.push(['onLoad', (api) => { // Executed when a push notification is displayed. Pushwoosh.addEventHandler('receive-push', (payload) => { console.log('Triggered event: receive-push', payload.notification); });}]);알림 이벤트
Anchor link to사용자가 푸시 알림을 열거나 닫았는지 추적합니다.
Pushwoosh.push(['onLoad', (api) => { // Executed when a user clicks on notification. Pushwoosh.addEventHandler('open-notification', (payload) => { console.log('Triggered event: open-notification', payload.notification); });
// Executed when a user closes a push notification. Pushwoosh.addEventHandler('hide-notification', (payload) => { console.log('Triggered event: hide-notification', payload.notification); });}]);받은 편지함 이벤트
Anchor link to받은 편지함으로 전송된 알림을 추적합니다.
Pushwoosh.push(['onLoad', (api) => { // Executed by ServiceWorker after the Inbox Message is received and saved to indexedDB. Pushwoosh.addEventHandler('receive-inbox-message', (payload) => { console.log('Triggered event: receive-inbox-message', payload.message); });
// Executed after the Inbox is updated automatically while the page is loading. Pushwoosh.addEventHandler('update-inbox-messages', (payload) => { console.log('Triggered event: receive-inbox-message', payload.messages); });}]);사용자 지정 구독 팝업 이벤트
Anchor link to사용자 지정 구독 팝업 이벤트 처리에 대한 자세한 내용은 사용자 지정 구독 팝업 이벤트 가이드를 참조하십시오.
웹 팝업 이벤트
Anchor link toPushwoosh.push(['onLoad', (api) => { // Executed once web popups have loaded and the automatic display pipeline has run for the current page Pushwoosh.addEventHandler('web-popups-ready', () => { console.log('Triggered event: web-popups-ready'); });
// Executed when a web popup is shown, automatically or via webPopups.show() Pushwoosh.addEventHandler('show-web-popup', (payload) => { console.log('Triggered event: show-web-popup', payload.code, payload.trigger); // trigger: 'auto' | 'api' });
// Executed when a web popup is hidden Pushwoosh.addEventHandler('hide-web-popup', (payload) => { console.log('Triggered event: hide-web-popup', payload.code, payload.reason); // reason: 'user' | 'api' | 'preempted' });}]);웹 푸시 SDK가 초기화된 후 Pushwoosh API에 다음 호출을 할 수 있습니다. 모든 메서드는 Promise 객체를 반환합니다.
Pushwoosh.push((api) => { // Set tags for a user api.setTags({ 'Tag Name 1': 'value1', 'Tag Name 2': 'value2' });
// Get tags for a user from server api.getTags();
// Register user ID api.registerUser('user123');
// Register user email api.registerEmail('user@example.com');
// Register SMS number api.registerSmsNumber('+15551234567');
// Register WhatsApp number api.registerWhatsappNumber('+1234567890');
// Post an Event api.postEvent('myEventName', {attributeName: 'attributeValue'});
//Unregister from notifications api.unregisterDevice();
// Set the device language (overrides the value in the "Language" Tag) api.setLanguage('es');
// Alternatively Multi-register user with devices and channels api.multiRegisterDevice({ user_id: 'user123', email: 'user@example.com', sms_phone_number: '+1234567890', tags: { 'UserType': { operation: TTagOperationSet, value: 'Premium' }, 'Interests': { operation: TTagOperationAppend, values: ['sports', 'technology'] } } });});multiRegisterDevice
Anchor link to단일 API 호출로 여러 기기 및 메시징 채널이 있는 사용자 프로필을 등록할 수 있는 향상된 등록 메서드입니다. 이 메서드는 크로스 플랫폼 애플리케이션이나 옴니채널 메시징 전략을 구현할 때 특히 유용합니다.
Pushwoosh.push((api) => { api.multiRegisterDevice({ user_id: 'user123', // Optional: User identifier email: 'user@example.com', // Optional: Email for email messaging sms_phone_number: '+1234567890', // Optional: SMS phone number (E.164 format) whatsapp_phone_number: '+1234567890', // Optional: WhatsApp number (E.164 format) kakao_phone_number: '+1234567890', // Optional: KakaoTalk number (E.164 format) language: 'en', // Optional: Language code (ISO 639-1) timezone: 'America/New_York', // Optional: Timezone identifier city: 'New York', // Optional: City for targeting country: 'US', // Optional: Country for targeting state: 'NY', // Optional: State for targeting tags: { // Optional: Tag values with operations 'UserType': { operation: TTagOperationSet, // Set tag value (0) value: 'Premium' }, 'Interests': { operation: TTagOperationAppend, // Append to tag value (1) values: ['sports', 'technology'] }, 'LoginCount': { operation: TTagOperationIncrement, // Increment tag value (3) value: '1' } }, push_devices: [ // Optional: Array of push devices { hwid: 'web-device-456', platform: TPlatformChrome, // Chrome platform (11) push_token: 'fcm-token-here', app_version: '2.1.0', platformData: { public_key: 'web-push-public-key', auth_token: 'web-push-auth-token', browser: 'chrome' } } ] }) .then((response) => { console.log('Multi-registration successful:', response); }) .catch((error) => { console.error('Multi-registration failed:', error); });});플랫폼 유형:
TPlatformSafari(10): Safari 플랫폼TPlatformChrome(11): Chrome 플랫폼TPlatformFirefox(12): Firefox 플랫폼
태그 작업 유형:
TTagOperationSet(0): 태그 값 설정 (기존 값 대체)TTagOperationAppend(1): 태그 값에 추가 (목록에 추가)TTagOperationRemove(2): 태그 값 제거 (목록에서 제거)TTagOperationIncrement(3): 태그 값 증가 (숫자 증가)
이점:
- 단일 API 호출: 여러 기기와 채널을 한 번에 등록
- 원자적 작업: 모든 등록이 함께 성공하거나 실패
- 사용자 중심: 모든 기기를 단일 사용자 프로필과 연결
- 고급 태깅: 복잡한 태그 작업 지원
- 크로스 플랫폼: 여러 플랫폼을 동시에 처리
Pushwoosh로 태그를 보내는 예시:
Pushwoosh.push((api) => { var myCustomTags = { 'Tag 1': 123, 'Tag 2': 'some string' }; api.setTags(myCustomTags) .then((res) => { var skipped = res && res.skipped || []; if (!skipped.length) { console.log('success'); } else { console.warn('skipped tags:', skipped); } }) .catch((err) => { console.error('setTags error:', err); });});태그 값 증가
Anchor link to숫자 태그의 값을 증가시키려면 operation 매개변수를 ‘increment’ 값과 함께 다음과 같이 사용합니다:
Pushwoosh.push((api) => { api.setTags({ 'Tag 1': { operation: 'increment', value: 1 } })});태그 값 추가
Anchor link to기존 목록 태그에 새 값을 추가하려면 operation 매개변수를 ‘append’ 값과 함께 다음과 같이 사용합니다:
Pushwoosh.push((api) => { api.setTags({ 'Tag 3': { operation: 'append', value: ['Value3'] } })});태그 값 제거
Anchor link to목록 태그에서 값을 제거하려면 operation 매개변수를 ‘remove’ 값과 함께 다음과 같이 사용합니다:
Pushwoosh.push((api) =>{ api.setTags({ 'Tag 3': { operation: 'remove', value: ['Value2'] } })});공개 메서드
Anchor link toPushwoosh.subscribe()
이 메서드는 사용자에게 푸시 알림 권한을 요청하는 데 사용됩니다. 사용자가 이미 구독한 경우 메서드 실행이 중지됩니다.
사용자가 아직 푸시를 구독하지 않은 경우:
1. 푸시 알림 권한이 요청됩니다.

2. 사용자가 알림을 허용하면 onSubscribe 이벤트가 트리거됩니다.
SDK 초기화 중에 autoSubscribe: true가 설정된 경우 Pushwoosh.subscribe()가 자동으로 실행됩니다.
초기화 중에 autoSubscribe: false 매개변수를 사용하여 사용자에게 수동으로 푸시 구독을 요청하도록 선택한 경우 이 메서드를 호출하십시오:
<button onclick="Pushwoosh.subscribe()">Subscribe</button><script> Pushwoosh.push(['onSubscribe', (api) => { console.log('User successfully subscribed'); }]);</script>Pushwoosh.unsubscribe()
/unregisterDevice메서드가 실행됩니다.onUnsubscribe이벤트가 트리거됩니다.
<button onclick="Pushwoosh.unsubscribe()">Unsubscribe</button><script type="text/javascript"> Pushwoosh.push(['onUnsubscribe', (api) => { console.log('User successfully unsubscribed'); }]);</script>Pushwoosh.isSubscribed()
사용자가 구독했는지 확인하고 true/false 플래그를 반환합니다.
Pushwoosh.isSubscribed().then((isSubscribed) => { console.log('isSubscribed', isSubscribed);});Pushwoosh.getHWID()
Pushwoosh HWID를 반환합니다.
Pushwoosh.getHWID().then((hwid) => { console.log('hwid:', hwid);});Pushwoosh.getPushToken()
푸시 토큰이 있는 경우 반환합니다.
Pushwoosh.getPushToken().then((pushToken) => { console.log('pushToken:', pushToken);});Pushwoosh.getUserId()
사용 가능한 경우 User ID를 반환합니다.
Pushwoosh.getUserId().then((userId) => { console.log('userId:', userId);});Pushwoosh.getParams()
다음 매개변수 목록을 반환합니다:
Pushwoosh.getParams().then((params) => { params = params || {}; var hwid = params.hwid; var pushToken = params.pushToken; var userId = params.userId;});Pushwoosh.isAvailableNotifications()
브라우저가 Pushwoosh WebSDK 3.0을 지원하는지 확인하고 ‘true’ 또는 ‘false’를 반환합니다.
Pushwoosh.isAvailableNotifications() // true/falseInboxMessages 메서드
Anchor link tomessagesWithNoActionPerformedCount(): Promise<number>
열린 메시지 수를 반환합니다.
Pushwoosh.pwinbox.messagesWithNoActionPerformedCount() .then((count) => { console.log(`${count} messages opened`); });unreadMessagesCount()
읽지 않은 메시지 수를 반환합니다.
Pushwoosh.pwinbox.unreadMessagesCount() .then((count) => { console.log(`${count} messages unread`); });messagesCount(): Promise<number>
총 메시지 수를 반환합니다.
Pushwoosh.pwinbox.messagesCount() .then((count) => { console.log(`${count} messages`); });loadMessages(): Promise<Array>
삭제되지 않은 메시지 목록을 로드합니다.
Pushwoosh.pwinbox.loadMessages() .then(() => { console.log('Messages have been loaded'); });readMessagesWithCodes(codes: Array<string>): Promise<void>
Inbox_Ids로 메시지를 읽음으로 표시합니다.
Pushwoosh.pwinbox.readMessagesWithCodes(codes) .then(() => { console.log('Messages have been read'); });performActionForMessageWithCode(code: string): Promise<void>
메시지에 할당된 작업을 수행하고 메시지를 읽음으로 표시합니다.
Pushwoosh.pwinbox.performActionForMessageWithCode(code) .then(() => { console.log('Action has been performed'); });deleteMessagesWithCodes(codes: Array<string>): Promise<void>
메시지를 삭제됨으로 표시합니다.
Pushwoosh.pwinbox.deleteMessagesWithCodes([code]) .then(() => { console.log('Messages have been deleted'); });syncMessages(): Promise<void>
서버와 메시지를 동기화합니다.
Pushwoosh.pwinbox.syncMessages() .then(() => { console.log('Messages have been synchronized'); });WebPopups 메서드
Anchor link to프로그래밍 방식 웹 팝업 API는 init 객체에 webPopups: {enable: true}가 필요하며, web-popups-ready 이벤트가 발생한 후 Pushwoosh.moduleRegistry.webPopups를 통해 사용할 수 있습니다.
show(code: string): Promise<boolean>
모든 표시 조건(지연, 페이지 규칙, 기기/방문자 유형, 빈도 제한, 트리거 유형)을 무시하고 즉시 팝업을 표시합니다. 공간을 만들기 위해 이미 보이는 팝업을 닫습니다. 팝업을 표시할 수 없을 때 거부하는 대신 false를 반환합니다.
Pushwoosh.moduleRegistry.webPopups.show('popup_code') .then((shown) => console.log('Popup shown:', shown));hide(code?: string): boolean
보이는 팝업을 숨깁니다. code가 전달되면 보이는 팝업과 일치할 때만 숨깁니다. 숨겨진 것이 없으면 false를 반환합니다.
Pushwoosh.moduleRegistry.webPopups.hide();hideAll(): boolean
보이는 팝업을 숨기고 현재 페이지 로드에 대해 아직 보류 중인 모든 것을 해제합니다. 그 후에도 show()는 계속 작동합니다.
Pushwoosh.moduleRegistry.webPopups.hideAll();isVisible(code?: string): boolean
팝업이 현재 보이는지 확인합니다. code가 없으면 어떤 팝업이든 보이는지 확인합니다.
Pushwoosh.moduleRegistry.webPopups.isVisible('popup_code');getVisibleCode(): string | null
현재 화면에 있는 팝업의 코드를 반환하거나, 보이는 것이 없으면 null을 반환합니다.
Pushwoosh.moduleRegistry.webPopups.getVisibleCode();getAvailableCodes(): Array<string>
서버가 이 기기에 대해 반환한 모든 팝업의 코드를 반환합니다.
Pushwoosh.moduleRegistry.webPopups.getAvailableCodes();getState(): object
웹 팝업의 상태 스냅샷을 반환합니다: visible (화면의 코드, 또는 null), queued (표시 슬롯을 기다리는 코드), waiting (지연 타이머가 설정된 코드), available (서버가 반환한 모든 코드).
Pushwoosh.moduleRegistry.webPopups.getState();프로그레시브 웹 앱(PWA) 지원
Anchor link toPushwoosh를 프로그레시브 웹 애플리케이션(PWA)에 통합하려면 아래 설명된 단계를 따르십시오.
1. 서비스 워커 파일의 경로를 복사합니다:
if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/service-worker.js') // <- your service worker url });}그런 다음, WebSDK를 초기화하는 동안 다음과 같이 serviceWorkerUrl 매개변수를 사용합니다:
var Pushwoosh = Pushwoosh || [];Pushwoosh.push(['init', { logLevel: 'error', applicationCode: 'XXXXX-XXXXX', safariWebsitePushID: 'web.com.example.domain', defaultNotificationTitle: 'Pushwoosh', defaultNotificationImage: 'https://yoursite.com/img/logo-medium.png', serviceWorkerUrl: '/service-worker.js', // <- your service worker url}]);WebSDK는 새 서비스 워커를 즉시 등록하지 않습니다. 서비스 워커는 필요할 때 등록됩니다:
- 기기가 푸시 토큰을 받을 때 (기기 등록 또는 재구독 시),
- 푸시 토큰이 삭제될 때 (사용자 기반에서 기기 제거 시).
서버 요청 수를 줄여 페이지 로딩 속도를 높입니다.
브라우저는 두 개의 다른 서비스 워커를 동시에 등록하는 것을 허용하지 않으므로(자세히 보기: https://github.com/w3c/ServiceWorker/issues/921), PWA가 올바르게 작동하려면 코드베이스와 Pushwoosh 코드베이스에 공통 서비스 워커를 등록해야 합니다.
2. 서비스 워커에 다음 문자열을 추가합니다(시작 또는 끝 부분, 상관없음):
importScripts('https://cdn.pushwoosh.com/webpush/v3/pushwoosh-service-worker.js' + self.location.search);이렇게 하면 서비스 워커가 Pushwoosh 서비스를 통해 전송된 푸시 알림을 수신하고 처리할 수 있습니다.
Google Tag Manager에서 설치하기
Anchor link toGoogle Tag Manager에서 다음 코드를 사용하여 Pushwoosh SDK를 초기화합니다. 사용자 지정 HTML 태그를 만들고 아래 코드를 붙여넣습니다. Pushwoosh 애플리케이션 코드, Safari 웹사이트 ID 및 기본 알림 이미지 URL을 변경해야 합니다.
또한 높은 태그 실행 우선순위(예: 100)를 설정하고 모든 페이지에서 트리거하십시오. 아래 스크린샷을 참조하십시오.복사
<script type="text/javascript" src="//cdn.pushwoosh.com/webpush/v3/pushwoosh-web-notifications.js" async></script><script type="text/javascript"> var Pushwoosh = Pushwoosh || []; Pushwoosh.push(['init', { logLevel: 'error', applicationCode: 'XXXXX-XXXXX', safariWebsitePushID: 'web.com.example.domain', defaultNotificationTitle: 'Pushwoosh', defaultNotificationImage: 'https://yoursite.com/img/logo-medium.png', autoSubscribe: true, subscribeWidget: { enable: false }, userId: 'user_id' }]);</script>