메인 콘텐츠로 건너뛰기

개요

이 가이드에서는 OneSignal 푸시 알림을 Vue.js 애플리케이션에 통합하는 방법을 설명합니다. Service Worker 구성 및 TypeScript 지원을 포함한 주요 설정 고려 사항과 함께 공식 OneSignal Vue 플러그인을 사용하여 Vue 2 및 Vue 3를 모두 다룹니다.

요구 사항

  • 구성된 OneSignal 앱 및 플랫폼. 시작하려면 웹 푸시 설정을 참조하세요.

Vue 호환성

Vue 환경과 호환되는 플러그인 버전을 설치했는지 확인하세요.
VueOneSignal Plugin
2onesignal-vue
3onesignal-vue3

설치

선호하는 패키지 관리자를 통해 설치하세요:
yarn add onesignal-vue
# or yarn add @onesignal/onesignal-vue3

초기화

OneSignal 서비스를 가져와서 루트 컴포넌트에서 초기화하세요. init 함수는 OneSignal이 로드될 때 해결되는 프로미스를 반환합니다. 키 및 ID에서 찾을 수 있는 OneSignal 앱 ID로 YOUR_APP_ID를 바꾸세요.
import Vue from 'vue'
import OneSignalVue from 'onesignal-vue'

Vue.use(OneSignalVue);

new Vue({
  render: h => h(App),
  beforeMount() {
    this.$OneSignal.init({ appId: 'YOUR_APP_ID' });
  }
}).$mount('#app')
//Example 1
await this.$OneSignal.init({ appId: 'YOUR_APP_ID' });
// do other stuff

//Example 2
this.$OneSignal.init({ appId: 'YOUR_APP_ID' }).then(() => {
  // do other stuff
});
OneSignal 플러그인은 애플리케이션 내부에서 액세스할 수 있는 $OneSignal 전역 속성을 자동으로 노출합니다.

Composition API

setup 내에서 호출할 수 있는 useOneSignal() 훅을 통해 Vue의 Composition API를 활용할 수도 있습니다.

init 옵션 사용자 지정

추가 init 매개변수로 초기화를 사용자 지정할 수 있습니다.

Service Worker 설정

아직 수행하지 않았다면 사이트에 추가할 OneSignal Service Worker 파일을 다운로드해야 합니다. OneSignalSDKWorker.js 파일은 공개적으로 액세스할 수 있어야 합니다. public 디렉토리, 최상위 루트 또는 하위 디렉토리에 넣을 수 있습니다. 그러나 파일을 하위 디렉토리에 배치하거나 사이트에 다른 Service Worker가 있는 경우 경로를 지정해야 합니다. 자세한 내용은 OneSignal Service Worker를 참조하세요.
옵션설명
serviceWorkerParamOneSignal worker가 제어하는 범위입니다. 권장 사항: 사용자 지정 하위 경로를 사용하세요(예: "/onesignal/").
serviceWorkerPath호스팅된 OneSignal Service Worker 파일의 경로입니다(예: "onesignal/OneSignalSDKWorker.js"). 공개적으로 액세스할 수 있어야 합니다.
예시:
this.$OneSignal.init({
  appId: 'YOUR-ONESIGNAL-APP-ID',
  serviceWorkerParam: {
    scope: '/onesignal/'
  },
  serviceWorkerPath: 'onesignal/OneSignalSDKWorker.js'
});

Worker 호스팅

  • 공개 루트(기본값): /OneSignalSDKWorker.js
  • 사용자 지정 폴더(권장): 예: 이전 단계에서 설정한 대로 /onesignal/OneSignalSDKWorker.js.

Service Worker 호스팅 확인

브라우저에서 경로를 방문하여 액세스할 수 있는지 확인하세요. 루트를 사용한 경우:
https://your-site.com/OneSignalSDKWorker.js
예시 경로를 사용하는 경우:
https://your-site.com/onesignal/OneSignalSDKWorker.js
유효한 JavaScript를 반환해야 합니다.

중요 사항

  • 개발 환경에서 중복 초기화 방지
    • 개발 환경에서 테스트할 때 OneSignal SDK가 두 번 초기화되어 콘솔 오류가 발생할 수 있습니다.
    • 이는 <React.StrictMode>가 개발 환경에서 효과를 두 번 실행하기 때문에 발생합니다. 이를 해결하려면 개발 중에 루트 컴포넌트에서 <React.StrictMode>를 제거하세요.
Strict 모드는 개발 환경에만 영향을 미치며 프로덕션 빌드에는 영향을 미치지 않습니다.

Testing the OneSignal SDK integration

This guide helps you verify that your OneSignal SDK integration is working correctly by testing push notifications and subscription registration.

Check web push subscriptions

1

Launch your site on a test device.

  • Use Chrome, Firefox, Edge, or Safari while testing.
  • Do not use Incognito or private browsing mode. Users cannot subscribe to push notifications in these modes.
  • The prompts should appear based on your permission prompts configuration.
  • Click Allow on the native prompt to subscribe to push notifications.

Web push native permission prompt

2

Check your OneSignal dashboard

Check the OneSignal dashboard:
  • Go to Audience > Subscriptions.
  • You should see a new entry with the status Subscribed.

Dashboard showing subscription with 'Subscribed' status

You have successfully created a web push subscription. Web push subscriptions are created when users first subscribe to push notifications on your site.

Set up test subscriptions

Test subscriptions are helpful for testing a push notification before sending a message.
1

Add to Test Subscriptions.

In the dashboard, next to the subscription, click the Options (three dots) button and select Add to Test Subscriptions.

Adding a device to Test Subscriptions

2

Name your subscription.

Name the subscription so you can easily identify your device later in the Test Subscriptions tab.

Dashboard showing the 'Name your subscription' field

3

Create a test users segment.

Go to Audience > Segments > New Segment.
4

Name the segment.

Name the segment Test Users (the name is important because it will be used later).
5

Add the Test Users filter and click Create Segment.

Creating a 'Test Users' segment with the Test Users filter

You have successfully created a segment of test users. We can now test sending messages to this individual device and groups of test users.

Send test push via API

1

Get your App API Key and App ID.

In your OneSignal dashboard, go to Settings > Keys & IDs.
2

Update the provided code.

Replace YOUR_APP_API_KEY and YOUR_APP_ID in the code below with your actual keys. This code uses the Test Users segment we created earlier.
curl -X \
POST --url 'https://api.onesignal.com/notifications' \
 --header 'content-type: application/json; charset=utf-8' \
 --header 'authorization: Key YOUR_APP_API_KEY' \
 --data \
 '{
  "app_id": "YOUR_APP_ID",
  "target_channel": "push",
  "name": "Testing basic setup",
  "headings": {
  	"en": "👋"
  },
  "contents": {
    "en": "Hello world!"
  },
  "included_segments": [
    "Test Users"
  ],
  "chrome_web_image": "https://avatars.githubusercontent.com/u/11823027?s=200&v=4"
}'
3

Run the code.

Run the code in your terminal.
4

Check images and confirmed delivery.

If all setup steps were completed successfully, the test subscriptions should receive a notification.
Only Chrome supports images. Images will appear small in the collapsed notification view. Expand the notification to see the full image.

Expanded push notification with image on Chrome macOS

5

Check for confirmed delivery.

In your dashboard, go to Delivery > Sent Messages, then click the message to view stats.You should see the confirmed stat, meaning the device received the push.
Safari does not support Confirmed Delivery.

Delivery stats showing confirmed delivery

If you’re on a Professional plan or higher, scroll to Audience Activity to see subscription-level confirmation:

Confirmed delivery at the device level in Audience Activity

You have successfully sent a notification via our API to a segment.
Need help? Contact support@onesignal.com with the following information:
  • Copy-paste the API request and response into a .txt file
  • Your Subscription ID
  • Your website URL with the OneSignal code
We’ll be happy to help!

User identification

Previously, we demonstrated how to create web push Subscriptions. Now we’ll expand to identifying Users across all their subscriptions (including push, email, and SMS) using the OneSignal SDK. We’ll cover External IDs, tags, multi-channel subscriptions, privacy, and event tracking to help you unify and engage users across platforms.

Assign External ID

Use an External ID to identify users consistently across devices, email addresses, and phone numbers using your backend’s user identifier. This ensures your messaging stays unified across channels and 3rd party systems (especially important for Integrations). Set the External ID with our SDK’s login method each time they are identified by your app.
OneSignal generates unique read-only IDs for subscriptions (Subscription ID) and users (OneSignal ID).As users download your app on different devices, subscribe to your website, and/or provide you email addresses and phone numbers outside of your app, new subscriptions will be created.Setting the External ID via our SDK is highly recommended to identify users across all their subscriptions, regardless of how they are created.

Add data tags

Tags are key-value pairs of string data you can use to store user properties (like username, role, or preferences) and events (like purchase_date, game_level, or user interactions). Tags power advanced Message Personalization and Segmentation allowing for more advanced use cases. Set tags with our SDK addTag and addTags methods as events occur in your app. In this example, the user reached level 6 identifiable by the tag called current_level set to a value of 6.

A user profile in OneSignal with a tag called "current_level" set to "6"

We can create a segment of users that have a level of between 5 and 10, and use that to send targeted and personalized messages:

Segment editor showing a segment targeting users with a current_level value of greater than 4 and less than 10


Screenshot showing a push notification targeting the Level 5-10 segment with a personalized message

Add email and/or SMS subscriptions

Earlier we saw how our SDK creates web push subscriptions to send push. You can also reach users through emails and SMS channels by creating the corresponding subscriptions. If the email address and/or phone number already exist in the OneSignal app, the SDK will add it to the existing user, it will not create duplicates. You can view unified users via Audience > Users in the dashboard or with the View user API.

A user profile with push, email, and SMS subscriptions unified by External ID

Best practices for multi-channel communication
  • Obtain explicit consent before adding email or SMS subscriptions.
  • Explain the benefits of each communication channel to users.
  • Provide channel preferences so users can select which channels they prefer.

To control when OneSignal collects user data, use the SDK’s consent gating methods: See our Privacy & security docs for more on:

Listen to push, user, and in-app events

Use SDK listeners to react to user actions and state changes. The SDK provides several event listeners for you to hook into. See our SDK reference guide for more details.

Push notification events

User state changes


Advanced setup & capabilities

Explore more capabilities to enhance your integration:

Web SDK setup & reference

Make sure you’ve enabled all key features by reviewing the Web push setup guide. For full details on available methods and configuration options, visit the Web SDK reference.
Congratulations! You’ve successfully completed the Web SDK setup guide.

도움이 필요하신가요?지원 팀과 채팅하거나 support@onesignal.com으로 이메일을 보내주세요.다음을 포함해 주세요:
  • 발생한 문제의 세부 정보 및 재현 단계(가능한 경우)
  • OneSignal 앱 ID
  • External ID 또는 Subscription ID(해당하는 경우)
  • OneSignal 대시보드에서 테스트한 메시지의 URL(해당하는 경우)
  • 관련 로그 또는 오류 메시지
기꺼이 도와드리겠습니다!