For AI agents: a documentation index is available at /docs/llms.txt. Append .md to any page URL for markdown, or send Accept: text/markdown.
SDK 플러그인
플러그인은 Amplitude의 동작을 확장합니다. 이 유연한 패턴은 이벤트 보강, 트랜스포메이션, 필터링, 타사 대상으로의 라우팅 등을 지원합니다.
플러그인 메서드
플러그인은 setup()와 execute()라는 두 가지 메서드를 가진 객체입니다.
Plugin.setup
이 메서드는 플러그인을 사용할 준비를 하고 config를 매개변수로 받습니다. undefined를 반환합니다. 일반적인 용도는 config에서 구성을 복사하거나 플러그인 종속성을 인스턴스화하는 것입니다. 플러그인을 amplitude.add()에 등록할 때 Amplitude가 이 메서드를 호출합니다.
Plugin.execute
이 메서드는 이벤트를 처리하고 매개변수로 event을 받습니다. 보강 유형 플러그인의 경우 수정되거나 보강된 이벤트를 반환합니다. 대상 유형 플러그인의 경우, event(BaseEvent), code(number), 및 message(string) 키가 있는 맵을 반환합니다. Amplitude는 클라이언트 인터페이스를 통해 계측된 Identify, GroupIdentify 및 Revenue 이벤트를 포함하여 각 이벤트에 대해 이 메서드를 호출합니다.
amplitude.add()를 사용하여 Ampli에 플러그인을 추가하십시오. 원하는 만큼 플러그인을 추가할 수 있습니다. 각 플러그인은 플러그인 유형에 따라 순서대로 실행됩니다.
amplitude.add(yourPlugin())
execute()가 이벤트를 반환하지 않는 경우 해당 이벤트는 나머지 플러그인을 통해 전파되지 않습니다.
보강 플러그인
보강 플러그인은 이벤트 객체의 속성을 수정하거나 이벤트를 삭제합니다. 이벤트 객체에 사용할 수 있는 키에 대해서는 HTTP V2 API 참조 문서를 확인하십시오.
이벤트 삭제
import * as amplitude from '@amplitude/analytics-browser';
import {PluginType} from '@amplitude/analytics-types';
class FilterEventsPlugin {
name = 'filter-events-plugin';
type = PluginType.ENRICHMENT;
async setup(config) {
return undefined;
}
async execute(event) {
// ignore events with a certain property
if (event.event_properties['ignore'] === true){
// returning null will prevent this event from being processed by subsequent plugins
return null;
}
// Allow other events to be processed and sent to destination plugins
return event;
}
}
amplitude.add(new FilterEventsPlugin());
amplitude.init('API_KEY');
범용 사용자 속성 설정
import * as amplitude from '@amplitude/analytics-browser';
import {PluginType} from '@amplitude/analytics-types';
class PropertiesEnrichmentPlugin {
name = 'properties-plugin';
type = PluginType.ENRICHMENT;
async setup(_, amplitude) {
if (shouldSetUserProperties) {
const identifyEvent = new amplitude.Identify();
identifyEvent.set("testKey", "testValue");
amplitude.identify(identifyEvent);
}
return undefined;
}
async execute(event) {
return event
}
}
amplitude.add(new PropertiesEnrichmentPlugin());
amplitude.init('API_KEY');
개인 식별 정보(PII)를 제거하십시오.
import * as amplitude from '@amplitude/analytics-browser';
import {PluginType} from '@amplitude/analytics-types';
class FilterEventsPlugin {
name = 'remove-PII-plugin';
type = PluginType.ENRICHMENT;
async setup(config) {
return undefined;
}
async execute(event) {
// remove PII on the event
if(event.user_properties['phone']) {
delete event.user_properties['phone'];
// set a new prop to mark this event as modified
event.event_properties['pii-removed'] = true;
}
// return modified event with PII removed
return event
}
}
amplitude.init('API_KEY');
amplitude.add(new FilterEventsPlugin());
Ampli v2를 사용하여 이벤트 수준 그룹 전송
이 예제에서는 Ampli V2에서 이벤트 수준 그룹을 전송하는 방법을 보여줍니다. SDK에서 이벤트 수준 그룹을 전송하는 방식(Ampli 제외)은 다르게 작동합니다. 사용 방법에 대한 자세한 내용은 특정 SDK를 확인하세요.
import * as amplitude from '@amplitude/analytics-browser';
import {PluginType} from '@amplitude/analytics-types';
class EventLevelGroupPlugin {
name = 'group-plugin';
type = PluginType.ENRICHMENT;
async setup(config) {
return undefined;
}
async execute(event) {
event.groups = event.extra['groups'];
return event;
}
// Allow other events to be processed and sent to destination plugins
return event;
}
ampli.client.add(new EventLevelGroupPlugin());
const extra = {extra: { groups: ["test_group_name": "test_group_value"]}};
ampli.eventWithGroups({requiredNumber: 1.23, requiredBoolean: false}, extra);
목적지 플러그인
목적지 플러그인을 사용하여 이벤트를 타사 API로 전송합니다.
세그먼트로 전송
먼저, Segment의 가이드를 따라 Segment Analytics.js 2.0 웹 SDK를 설치하세요.
import { AnalyticsBrowser } from '@segment/analytics-next';
import { Types } from '@amplitude/analytics-browser';
export default class SegmentPlugin {
name = 'segment';
type = Types.PluginType.DESTINATION;
constructor(private readonly writeKey) {
// Create Segment tracker
this.segment = new AnalyticsBrowser();
}
async setup(config) {
this.segment.load({
writeKey: this.writeKey,
});
return;
}
execute(context) {
return new Promise(resolve => {
const {
event_type,
event_properties,
user_id,
user_properties,
groups,
group_properties,
} = context;
const callback = (ctx) => {
resolve({ event: context, code: 200, message: '' });
};
switch (event_type) {
case Types.SpecialEventType.IDENTIFY:
case Types.SpecialEventType.GROUP_IDENTIFY:
const groupValues = groups ? Object.values(groups) : [];
if (groupValues.length === 0) {
this.segment.identify(
user_id,
user_properties?.[Types.IdentifyOperation.SET],
{},
callback,
);
} else {
this.segment.group(
groupValues[0],
group_properties?.[Types.IdentifyOperation.SET],
{},
callback,
);
}
break;
case 'page':
// @ts-ignore
const { name, category, ...properties } = event_properties;
this.segment.page(category, name, properties, {}, callback);
break;
default:
this.segment.track(event_type, event_properties, {}, callback);
break;
}
});
}
}
Hotjar로 전송
시작하기 전에 Hotjar의 추적 코드를 참조하십시오.
import { PluginType } from "@amplitude/analytics-types"
import { default as hj } from "@hotjar/browser"
export class HotjarPlugin {
name = "hotjar"
type = PluginType.DESTINATION
constructor(siteId, hotjarVersion, debug = false) {
this.siteId = siteId
this.hotjarVersion = hotjarVersion
}
async setup() {
hj.init(this.siteId, this.hotjarVersion)
}
async execute(event) {
if (event.event_type === "$identify") {
const { user_id, device_id, user_properties } = event
const hotjarId = user_id || device_id || ""
hj.identify(hotjarId, user_properties || {})
} else {
hj.event(event.event_type)
}
return {
code: 0,
event: event,
message: "Event forwarded to Hotjar SDK"
}
}
}
Google 분석으로 전송
시작하기 전에 Google의 데이터 레이어에 대한 문서를 참조하세요.
import { PluginType } from "@amplitude/analytics-types"
export class GTMPlugin {
name = "google-tag-manager"
type = PluginType.DESTINATION
constructor(containerId) {
this.containerId = containerId
}
async setup() {
if (!window.dataLayer) {
window.dataLayer = window.dataLayer || []
window.dataLayer.push({
"gtm.start": new Date().getTime(),
event: "gtm.js"
})
const head = document.getElementsByTagName("head")[0],
script = document.createElement("script");
script.async = true
script.src =
`https://www.googletagmanager.com/gtm.js?id=${this.containerId}&l=datalayer`
head.insertBefore(script, head.firstChild)
}
}
async execute(event) {
window.dataLayer.push(event)
return {
code: 200,
event: event,
message: "Event pushed onto GTM Data Layer"
}
}
}
FullStory로 전송
시작하기 전에 FullStory의 브라우저 SDK에 대한 문서를 참조하십시오.
import { PluginType } from '@amplitude/analytics-types';
export class FullstoryPlugin {
constructor(fsOrg) {
this.name = 'fullstory';
this.type = PluginType.DESTINATION;
this.fsOrg = fsOrg;
this.FS = window.FS;
}
async setup() {
window._fs_host || (window._fs_host = "fullstory.com", window._fs_script = "edge.fullstory.com/s/fs.js", window._fs_org = this.fsOrg, window._fs_namespace = "FS", function (n, t, e, o, s, c, i, f) { e in n ? n.console && n.console.log && n.console.log('FullStory namespace conflict. Please set window["_fs_namespace"].') : ((i = n[e] = function (n, t, e) { i.q ? i.q.push([n, t, e]) : i._api(n, t, e); }).q = [], (c = t.createElement(o)).async = 1, c.crossOrigin = "anonymous", c.src = "https://" + _fs_script, (f = t.getElementsByTagName(o)[0]).parentNode.insertBefore(c, f), i.identify = function (n, t, e) { i(s, { uid: n }, e), t && i(s, t, e); }, i.setUserVars = function (n, t) { i(s, n, t); }, i.event = function (n, t, e) { i("event", { n: n, p: t }, e); }, i.anonymize = function () { i.identify(!1); }, i.shutdown = function () { i("rec", !1); }, i.restart = function () { i("rec", !0); }, i.log = function (n, t) { i("log", [n, t]); }, i.consent = function (n) { i("consent", !arguments.length || n); }, i.identifyAccount = function (n, t) { c = "account", (t = t || {}).acctId = n, i(c, t); }, i.clearUserCookie = function () { }, i.setVars = function (n, t) { i("setVars", [n, t]); }, i._w = {}, f = "XMLHTTPRequest", i._w[f] = n[f], f = "fetch", i._w[f] = n[f], n[f] && (n[f] = function () { return i._w[f].apply(this, arguments); }), i._v = "1.3.0"); }(window, document, window._fs_namespace, "script", "user"));
this.FS = window.FS;
}
async execute(event) {
if (event.event_type === '$identify') {
this.FS.identify(event.user_id);
}
else {
this.FS.event(event.event_type, event.event_properties);
}
return {
code: 200,
event: event,
message: 'Event forwarded to Fullstory',
};
}
}
지원되는 SDK
이 내용이 도움이 되었나요?