适用于 Application Insights JavaScript SDK 的“单击分析自动收集”插件Click Analytics Auto-collection plugin for Application Insights JavaScript SDK

此插件可自动跟踪网页上的单击事件,并使用 HTML 元素上的 data-* 属性来填充事件遥测数据。This plugin automatically tracks click events on web pages and uses data-* attributes on HTML elements to populate event telemetry.

入门Getting started

用户可通过 npm 设置“单击分析自动收集”插件。Users can set up the Click Analytics Auto-collection plugin via npm.

npm 设置npm setup

安装 npm 包:Install npm package:

npm install --save @microsoft/applicationinsights-clickanalytics-js @microsoft/applicationinsights-web

import { ApplicationInsights } from '@microsoft/applicationinsights-web';
import { ClickAnalyticsPlugin } from '@microsoft/applicationinsights-clickanalytics-js';

const clickPluginInstance = new ClickAnalyticsPlugin();
// Click Analytics configuration
const clickPluginConfig = {
  autoCapture: true
};
// Application Insights Configuration
const configObj = {
  instrumentationKey: "YOUR INSTRUMENTATION KEY",
  extensions: [clickPluginInstance],
  extensionConfig: {
    [clickPluginInstance.identifier]: clickPluginConfig
  },
};

const appInsights = new ApplicationInsights({ config: configObj });
appInsights.loadAppInsights();

如何有效使用此插件How to effectively use the plugin

  1. 从单击事件生成的遥测数据将作为 customEvents 存储在 Azure 门户的 Application Insights 部分。Telemetry data generated from the click events are stored as customEvents in the Application Insights section of the Azure portal.

  2. 系统根据以下规则填充 customEvent 的 nameThe name of the customEvent is populated based on the following rules:

    1. data-*-id 中提供的 id 将用作 customEvent 名称。The id provided in the data-*-id will be used as the customEvent name. 例如,如果单击的 HTML 元素的“data-sample-id”=“button1”,则“button1”将为 customEvent 名称。For example, if the clicked HTML element has the attribute "data-sample-id"="button1", then "button1" will be the customEvent name.
    2. 如果不存在这样的属性,并且配置中的 useDefaultContentNameOrId 设置为 true,则所选元素的 HTML 属性 id 或元素的内容名称将用作 customEvent 名称。If no such attribute exists and if the useDefaultContentNameOrId is set to true in the configuration, then the clicked element's HTML attribute id or content name of the element will be used as the customEvent name.
    3. 如果 useDefaultContentNameOrId 为 false,则 customEvent 名称将为“not_specified”。If useDefaultContentNameOrId is false, then the customEvent name will be "not_specified".

    提示

    建议将 useDefaultContentNameOrId 设置为 true,以生成有意义的数据。Our recommendations is to set useDefaultContentNameOrId to true for generating meaningful data.

  3. parentDataTag 执行两项操作:parentDataTag does two things:

    1. 如果此标记存在,此插件将从单击的元素的所有 HTML 父元素中提取 data-* 属性和值。If this tag is present, the plugin will fetch the data-* attributes and values from all the parent HTML elements of the clicked element.
    2. 为提升效率,该插件会将此标记用作标志,遇到此标记时,它将阻止自己向上处理 DOM(文档对象模型)。To improve efficiency, the plugin uses this tag as a flag, when encountered it will stop itself from further processing the DOM (Document Object Model) upwards.

    注意

    使用 parentDataTag 后,SDK 将开始在整个应用程序中查找父标记,而不只是在使用它的 HTML 元素中查找。Once parentDataTag is used, the SDK will begin looking for parent tags across your entire application and not just the HTML element where you used it.

  4. 用户提供的 customDataPrefix 应始终以 data- 开头,例如 data-sample-customDataPrefix provided by the user should always start with data-, for example data-sample-. 在 HTML 中,data-* 全局属性构成一类允许通过脚本在 HTML 及其 DOM 表示形式之间交换专有信息的属性,称为“自定义数据属性”。In HTML the data-* global attributes form a class of attributes called custom data attributes, that allow proprietary information to be exchanged between the HTML and its DOM representation by scripts. 旧版浏览器(Internet Explorer、Safari)会删除它不理解的属性,除非属性以 data- 开头。Older browsers (Internet Explorer, Safari) will drop attributes that it doesn't understand, unless they start with data-.

    data-* 中的 * 可能会被遵循 XML 名称生成规则的任意名称替换,但有以下限制:The * in data-* may be replaced by any name following the production rule of XML names with the following restrictions:

    • 名称不能以“xml”开头,无论这些字母是使用大写还是小写都是如此。The name must not start with "xml", whatever case is used for these letters.
    • 名称不能包含任何分号 (U+003A)。The name must not contain any semicolon (U+003A).
    • 名称不能包含大写字母。The name must not contain capital letters.

配置Configuration

名称Name 类型Type 默认Default 说明Description
autoCaptureautoCapture booleanboolean true 自动捕获配置。Automatic capture configuration.
回调 (callback)callback IValueCallbackIValueCallback NULLnull 回调配置。Callbacks configuration.
pageTagspageTags stringstring NULLnull 页标记。Page tags.
dataTagsdataTags ICustomDataTagsICustomDataTags NULLnull 提供的自定义数据标记用于替代捕获单击数据的默认标记。Custom Data Tags provided to override default tags used to capture click data.
urlCollectHashurlCollectHash booleanboolean falsefalse 启用 URL中“#”字符后的值的日志记录。Enables the logging of values after a "#" character of the URL.
urlCollectQueryurlCollectQuery booleanboolean falsefalse 启用 URL 查询字符串的日志记录。Enables the logging of the query string of the URL.
behaviorValidatorbehaviorValidator 功能Function NULLnull 用于验证 data-*-bhvr 值的回调函数。Callback function to use for the data-*-bhvr value validation. 有关详细信息,请参阅 behaviorValidator 部分For more information, go to behaviorValidator section.
defaultRightClickBhvrdefaultRightClickBhvr 字符串(或)数字string (or) number '''' 发生“右键单击”事件时的默认行为值。Default Behavior value when Right Click event has occurred. 如果元素具有 data-*-bhvr 属性,则将替代此值。This value will be overridden if the element has the data-*-bhvr attribute.
dropInvalidEventsdropInvalidEvents booleanboolean falsefalse 用于删除无有用单击数据的事件的标志。Flag to drop events that do not have useful click data.

IValueCallbackIValueCallback

名称Name 类型Type 默认Default 说明Description
pageNamepageName 功能Function NULLnull 用于替代默认 pageName 捕获行为的函数。Function to override the default pageName capturing behavior.
pageActionPageTagspageActionPageTags 功能Function NULLnull 用于增加在 pageAction 事件期间收集的默认 pageTags 的回调函数。A callback function to augment the default pageTags collected during pageAction event.
contentNamecontentName 功能Function NULLnull 用于填充自定义 contentName 的回调函数。A callback function to populate customized contentName.

ICustomDataTagsICustomDataTags

名称Name 类型Type 默认Default 要在 HTML 中使用的默认标记Default Tag to Use in HTML 说明Description
useDefaultContentNameOrIduseDefaultContentNameOrId booleanboolean falsefalse 不适用N/A 当特定元素未使用默认的 customDataPrefix 进行标记或用户未提供 customDataPrefix 时,收集 contentName 的标准 HTML 属性。Collects standard HTML attribute for contentName when a particular element is not tagged with default customDataPrefix or when customDataPrefix is not provided by user.
customDataPrefixcustomDataPrefix stringstring data- data-* 自动捕获使用所提供的前缀标记的元素的内容名称和值。Automatic capture content name and value of elements that are tagged with provided prefix. 例如,可以在 HTML 标记中使用 data-*-iddata-<yourcustomattribute>For example, data-*-id, data-<yourcustomattribute> can be used in the HTML tags.
aiBlobAttributeTagaiBlobAttributeTag stringstring ai-blob data-ai-blob 插件支持 JSON blob 属性,而不支持单个 data-* 属性。Plugin supports a JSON blob attribute instead of individual data-* attributes.
metaDataPrefixmetaDataPrefix stringstring NULLnull 不适用N/A 捕获时,自动捕获 HTML 标头的 meta 元素名称和带有所提供的前缀的内容。Automatic capture HTML Head's meta element name and content with provided prefix when capture. 例如,可以在 HTML meta 标记中使用 custom-For example, custom- can be used in the HTML meta tag.
captureAllMetaDataContentcaptureAllMetaDataContent booleanboolean falsefalse 不适用N/A 自动捕获所有 HTML 标头的 meta 元素名称和内容。Automatic capture all HTML Head's meta element names and content. 默认值为 false。Default is false. 如果启用此参数,则将替代所提供的 metaDataPrefix。If enabled this will override provided metaDataPrefix.
parentDataTagparentDataTag stringstring NULLnull 不适用N/A 遇到此标记时,将停止遍历 DOM,不再捕获元素的内容名称和值。Stops traversing up the DOM to capture content name and value of elements when encountered with this tag. 例如,可以在 HTML 标记中使用 data-<yourparentDataTag>For example, data-<yourparentDataTag> can be used in the HTML tags.
dntDataTagdntDataTag stringstring ai-dnt data-ai-dnt 捕获遥测数据的插件将忽略具有此属性的 HTML 元素。HTML elements with this attribute will be ignored by the plugin for capturing telemetry data.

behaviorValidatorbehaviorValidator

BehaviorValidator 函数会自动检查代码中标记的行为是否符合预定义的列表。The behaviorValidator functions automatically checks that tagged behaviors in code conform to a pre-defined list. 这样可以确保标记的行为与企业建立的分类一致。This ensures tagged behaviors are consistent with your enterprise's established taxonomy. 大多数 Azure Monitor 客户不需要使用,预计也不会使用该函数,但它可以用于高级场景。It is not required or expected that most Azure Monitor customers will use this, but it's available for advanced scenarios. 有三个不同的 behaviorValidator 回调函数作为此扩展的一部分公开。There are three different behaviorValidator callback functions exposed as part of this extension. 但如果公开的函数不能满足需求,用户可以使用自己的回调函数。However, users can use their own callback functions if the exposed functions do not solve your requirement. 这样做的目的是引入你自己的行为数据结构,当从数据标签中提取行为时,插件将使用此验证程序函数。The intent is to bring your own behaviors data structure, the plugin uses this validator function while extracting the behaviors from the data tags.

名称Name 说明Description
BehaviorValueValidatorBehaviorValueValidator 如果行为数据结构是字符串数组,请使用此回调函数。Use this callback function if your behaviors data structure is an array of strings.
BehaviorMapValidatorBehaviorMapValidator 如果行为数据结构为字典,则使用此回调函数。Use this callback function if your behaviors data structure is a dictionary.
BehaviorEnumValidatorBehaviorEnumValidator 如果行为数据结构是一个枚举,则使用此回调函数。Use this callback function if your behaviors data structure is an Enum.

behaviorValidator 的示例用法Sample usage with behaviorValidator

var clickPlugin = Microsoft.ApplicationInsights.ClickAnalyticsPlugin;
var clickPluginInstance = new clickPlugin();

// Behavior enum values
var behaviorMap = {
  UNDEFINED: 0, // default, Undefined

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Page Experience [1-19]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  NAVIGATIONBACK: 1, // Advancing to the previous index position within a webpage
  NAVIGATION: 2, // Advancing to a specific index position within a webpage
  NAVIGATIONFORWARD: 3, // Advancing to the next index position within a webpage
  APPLY: 4, // Applying filter(s) or making selections
  REMOVE: 5, // Applying filter(s) or removing selections
  SORT: 6, // Sorting content
  EXPAND: 7, // Expanding content or content container
  REDUCE: 8, // Sorting content
  CONTEXTMENU: 9, // Context Menu
  TAB: 10, // Tab control
  COPY: 11, // Copy the contents of a page
  EXPERIMENTATION: 12, // Used to identify a third party experimentation event
  PRINT: 13, // User printed page
  SHOW: 14, //  Displaying an overlay
  HIDE: 15, //  Hiding an overlay
  MAXIMIZE: 16, //  Maximizing an overlay
  MINIMIZE: 17, // Minimizing an overlay
  BACKBUTTON: 18, //  Clicking the back button

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Scenario Process [20-39]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  STARTPROCESS: 20, // Initiate a web process unique to adopter
  PROCESSCHECKPOINT: 21, // Represents a checkpoint in a web process unique to adopter
  COMPLETEPROCESS: 22, // Page Actions that complete a web process unique to adopter
  SCENARIOCANCEL: 23, // Actions resulting from cancelling a process/scenario

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Download [40-59]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  DOWNLOADCOMMIT: 40, // Initiating an unmeasurable off-network download
  DOWNLOAD: 41, // Initiating a download

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Search [60-79]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  SEARCHAUTOCOMPLETE: 60, // Auto-completing a search query during user input
  SEARCH: 61, // Submitting a search query
  SEARCHINITIATE: 62, // Initiating a search query
  TEXTBOXINPUT: 63, // Typing or entering text in the text box

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Commerce [80-99]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  VIEWCART: 82, // Viewing the cart
  ADDWISHLIST: 83, // Adding a physical or digital good or services to a wishlist
  FINDSTORE: 84, // Finding a physical store
  CHECKOUT: 85, // Before you fill in credit card info
  REMOVEFROMCART: 86, // Remove an item from the cart
  PURCHASECOMPLETE: 87, // Used to track the pageView event that happens when the CongratsPage or Thank You page loads after a successful purchase
  VIEWCHECKOUTPAGE: 88, // View the checkout page
  VIEWCARTPAGE: 89, // View the cart page
  VIEWPDP: 90, // View a PDP
  UPDATEITEMQUANTITY: 91, // Update an item's quantity
  INTENTTOBUY: 92, // User has the intent to buy an item
  PUSHTOINSTALL: 93, // User has selected the push to install option

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Authentication [100-119]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  SIGNIN: 100, // User sign-in
  SIGNOUT: 101, // User sign-out

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Social [120-139]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  SOCIALSHARE: 120, // "Sharing" content for a specific social channel
  SOCIALLIKE: 121, // "Liking" content for a specific social channel
  SOCIALREPLY: 122, // "Replying" content for a specific social channel
  CALL: 123, // Click on a "call" link
  EMAIL: 124, // Click on an "email" link
  COMMUNITY: 125, // Click on a "community" link

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Feedback [140-159]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  VOTE: 140, // Rating content or voting for content
  SURVEYCHECKPOINT: 145, // reaching the survey page/form

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Registration, Contact [160-179]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  REGISTRATIONINITIATE: 161, // Initiating a registration process
  REGISTRATIONCOMPLETE: 162, // Completing a registration process
  CANCELSUBSCRIPTION: 163, // Canceling a subscription
  RENEWSUBSCRIPTION: 164, // Renewing a subscription
  CHANGESUBSCRIPTION: 165, // Changing a subscription
  REGISTRATIONCHECKPOINT: 166, // Reaching the registration page/form

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Chat [180-199]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  CHATINITIATE: 180, // Initiating a chat experience
  CHATEND: 181, // Ending a chat experience

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Trial [200-209]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  TRIALSIGNUP: 200, // Signing-up for a trial
  TRIALINITIATE: 201, // Initiating a trial

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Signup [210-219]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  SIGNUP: 210, // Signing-up for a notification or service
  FREESIGNUP: 211, // Signing-up for a free service

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Referals [220-229]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  PARTNERREFERRAL: 220, // Navigating to a partner's web property

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Intents [230-239]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  LEARNLOWFUNNEL: 230, // Engaging in learning behavior on a commerce page (ex. "Learn more click")
  LEARNHIGHFUNNEL: 231, // Engaging in learning behavior on a non-commerce page (ex. "Learn more click")
  SHOPPINGINTENT: 232, // Shopping behavior prior to landing on a commerce page

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  // Video [240-259]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  VIDEOSTART: 240, // Initiating a video
  VIDEOPAUSE: 241, // Pausing a video
  VIDEOCONTINUE: 242, // Pausing or resuming a video.
  VIDEOCHECKPOINT: 243, // Capturing predetermined video percentage complete.
  VIDEOJUMP: 244, // Jumping to a new video location.
  VIDEOCOMPLETE: 245, // Completing a video (or % proxy)
  VIDEOBUFFERING: 246, // Capturing a video buffer event
  VIDEOERROR: 247, // Capturing a video error
  VIDEOMUTE: 248, // Muting a video
  VIDEOUNMUTE: 249, // Unmuting a video
  VIDEOFULLSCREEN: 250, // Making a video full screen
  VIDEOUNFULLSCREEN: 251, // Making a video return from full screen to original size
  VIDEOREPLAY: 252, // Making a video replay
  VIDEOPLAYERLOAD: 253, // Loading the video player
  VIDEOPLAYERCLICK: 254, //  Click on a button within the interactive player
  VIDEOVOLUMECONTROL: 255, //  Click on video volume control
  VIDEOAUDIOTRACKCONTROL: 256, // Click on audio control within a video
  VIDEOCLOSEDCAPTIONCONTROL: 257, //  Click on the closed caption control
  VIDEOCLOSEDCAPTIONSTYLE: 258, //  Click to change closed caption style
  VIDEORESOLUTIONCONTROL: 259, //  Click to change resolution

  ///////////////////////////////////////////////////////////////////////////////////////////////////
  //    Advertisement Engagement [280-299]
  ///////////////////////////////////////////////////////////////////////////////////////////////////
  ADBUFFERING: 283, // Ad is buffering
  ADERROR: 284, // Ad error
  ADSTART: 285, // Ad start
  ADCOMPLETE: 286, // Ad complete
  ADSKIP: 287, // Ad skipped
  ADTIMEOUT: 288, // Ad timed-out
  OTHER: 300 // Other
};

// Application Insights Configuration
var configObj = {
  instrumentationKey: "YOUR INSTRUMENTATION KEY",
  extensions: [clickPluginInstance],
  extensionConfig: {
    [clickPluginInstance.identifier]: {
      behaviorValidator: Microsoft.ApplicationInsights.BehaviorMapValidator(behaviorMap),
      defaultRightClickBhvr: 9
    },
  },
};
var appInsights = new Microsoft.ApplicationInsights.ApplicationInsights({
  config: configObj
});
appInsights.loadAppInsights();

示例应用Sample app

启用了“单击分析自动收集”插件的简单 Web 应用Simple web app with Click Analytics Auto-collection Plugin enabled.

后续步骤Next steps