If you find the article or project valuable, please consider adding it to the projectStar ⭐Or like this article 👍, thank you
Project Github Repository: github.com/darkXmo/bur…
Project NPM repository: @xmon/bury
Project Gitee Warehouse: Xmo/ Bury
If your project has a burying point that seriously impacts your business code, it’s time to consider using @xmon/bury
-
Non-trace buried point
-
Access the survey
-
Behavior monitoring
@xmon/ Bury doesn’t affect your business code, except for the necessary action of adding eventId, which is to add an ID to a project. You just need to add configuration!
Page behavior burying point, through the event monitoring to conduct behavior monitoring, currently can monitor events include
-
Click events
-
Page loading (Load & Unload)
-
Specific actions
-
Axios Request (Api)
-
Router
The installation
# yarn
yarn add @xmon/bury
# npm
npm install @xmon/bury
# pnpm
pnpm install @xmon/bury
Copy the code
Examples
Listening for general events (enable listening for clicks, page loads, specific behaviors)
// main.js
import { init } from "@xmon/bury";
import config from "./config.js";
const bury = init(config);
Copy the code
configuration
You need to specify the route you want to listen to in config, the route corresponds to the eventId of the event (incoming and outgoing).
At the same time, you need to specify the base parameters of the burial point. These parameters are usually the environment, the burial point version and the system version. These parameters are optional.
// config.js
import { initUrlMap } from "@xmon/bury";
// Use initUrlMap to configure the 1 page path and 2 page load, 3 page leave event ID that you want to listen to
initUrlMap([
{
path: "/user/:id".leave: "eventIdLeavePage".// Leave EventId
enter: "eventIdEnterPage".// Enter EventId},]);// Fill in the extra fields in the buried event return value. Normally you need to add the following configuration information
const config = {
environment: process.env.NODE_ENV,
version: "1.0.0"};export default config;
Copy the code
Listen to the Router
If you are using a Vue single-page application, you also need to listen for vue-Router hops, so you also need to pass in the Router instance as the second parameter
import router from "@/router";
// Register the router instance with bury
const bury = init(config, router);
Copy the code
Listening to the Api
If you need to listen to the Axios Api, encapsulate the Axios instance.
import axios from "axios";
import { trackApi } from "@xmon/bury";
const axiosInstance = axios.create({
...
});
// Remind @xmon/bury to listen for the axios example to make a request
trackApi(axiosInstance);
Copy the code
configuration
Similar to page listening, you also need to specify the API path you want to listen to and the corresponding eventId.
import { initUrlMap, initApiMap } from "@xmon/bury"; initUrlMap([ ... ] );// Use initApiMap to configure the url to listen on
initApiMap([
{
url: "/v3/search/anime".eventId: "eventIdApi",}]);const config = {
...
};
export default config;
Copy the code
It is important to note that the Query parameter is ignored both when listening to the page load and when listening to the API.
Listen for click events
<img :src="item.image_url" data-bupoint="eventId" />
Copy the code
For elements that need to listen for click events, add the data-bupoint attribute and inject eventId.
Listen for specific behavior
import { track } from "@xmon/bury";
// For a particular behavior, you need to wrap the behavior as a function, configure eventId, and then use track to listen for that function behavior
const increase = track(() = > {
console.log("I am tracked");
}, "eventId");
// The return value of track is the function you passed in, unchanged.
// increase = () => { console.log('I am tracked') }
Copy the code
For actions, you should encapsulate them using track, with the first argument being the function to encapsulate and the second argument being eventId.
Track returns the wrapped function after encapsulation.
A buried behavior occurs before a particular behavior is performed.
Immediately triggered
When the Tracked method is called, an Action type buried callback is immediately triggered.
import { tracked } from "@xmon/bury"; . tracked("eventId"); .Copy the code
Trigger the buried event callback
Triggering the listening behavior will also trigger the buried behavior, through onBury we can get the callback of the buried behavior.
Initialization (init
) before you can access itinstance
,track
,trackApi
,onBury
Otherwise undefined errors are thrown
import { onBury } from "@xmon/bury";
Once configured, you can use onBury to listen for events
// Once the URL you configured is loaded OR closed OR the API you are listening to is sent OR the event you are listening to is called OR the Dom you are watching is clicked => the callback registered in onBury will be triggered
onBury((value) = > {
// The BuryConfig section describes what values payload contains
const buryInfo = value.payload;
// Here is my sample behavior for buried callback. You should use your own behavior instead of the example
const queries = Object.entries(buryInfo)
.map(([key, value]) = > {
return key + "=" + encodeURI(value);
})
.join("&");
let img = new Image(1.1);
// Change the URL to the API of your backend buried point system
img.src = `http://exmapleApi.com/bury?` + queries;
// 3000ms timeout processing
setTimeout(() = > {
if(img && (! img.complete || ! img.naturalWidth)) { img.src =""; }},3000);
});
Copy the code
A callback function is registered in the onBury event whenever a monitored event occurs.
In this case, it will take payload from the callback parameter, encapsulate it and issue a Get request to IMG.
Because the onBeforeUnload method is executed just as the page is about to close, you cannot use Axios to initiate an asynchronous request at this point. But img and XMLHttpRequest synchronization requests can still be executed.
API
init
export const init = (config: BuryConfig, router? : VueRouter) = > Bury;
// Some of the configurations in the preconfiguration do not have default values. You can manually add presets through config
// These parameters are predefined in payload.
// You can also customize the parameters
export interfaceBuryConfig { eventId? :string; timestamp? :string; ua? :string; browser? :"MSIE" | "Firefox" | "Safari" | "Chrome" | "Opera"; referrer? :string; width? :string; height? :string; ip? :string; cityName? :string; isPhone? :"phone" | "pc"; userId? :string; pageUrl? :string; pageStayTime? :string; apiUrl? :string; // Only in the type === Api
}
Copy the code
BuryConfig by “@ fingerprintjs/fingerprintjs” module and “http://pv.sohu.com/cityjson?ie=utf-8” Api interface to get some default values, they are
timestamp
– Timestamp –new Date().getTime()
ua
– Client information (navigator. UserAgent). For details, seeDeveloper.mozilla.org/zh-CN/docs/…browser
– Browser typereferrer
– Quoted source -www.ruanyifeng.com/blog/2019/0…width
– Window widthheight
– Window heightip
– Client IP addresscityName
– Name of province and city of client – for example, “Nanjing, Jiangsu Province”isPhone
– Whether it is a mobile terminal. If yes, the value isphone
userId
– For details about the unique identifier of the client device, seeGithub.com/fingerprint…
For example, you can pass in project, Version, and Environment.
const bury = init({
project: "projectName".version: "v1".environment: process.env.NODE_ENV,
});
Copy the code
const bury = init(config, router);
Copy the code
config
Predefined parametersrouter
This parameter is optional if you want to listenVueRouter
Jump,
Bury.spy
When listening mode is enabled (do not enable it in production mode), you can view the return value of each buried event in the DevTools console
bury.spy();
Copy the code
initUrlMap
Initialize the page path of the listening URL and its array of Eventids.
All eventids are included in payload in the callback function argument
interface UrlMap: {
path: string; // The page URL is defined in the same way as path in VueRouterenter? :string; // Go to the EventId pageleave? :string; // Leave the EventId page} []Copy the code
url
Of the pageurl
Addresses, definitions followGithub.com/pillarjs/pa…Usually can andVueRouter
In thepath
Fill in the parameters by reference.enter
Enter the page of the burial pointeventId
leave
Leave the buried pageeventId
On the path github.com/pillarjs/pa…
initApiMap
interface ApiMap: {
url: string; // The url of the interfacemethod? : Method;// Method, such as' GET 'and' POST ', listens for all methods at that URL if not defined
eventId: string; // EventId when the interface is triggered} [] = [];Copy the code
url
Of the interfaceurl
addressmethod
Optional parametersMethod
, e.g.GET
POST
If it is not defined, it listens for iturl
Of all theMethod
eventId
The buried point interfaceeventId
track
Buried listening for events
function track<T extends () = >any> (fn: T, eventId: string) :T;
Copy the code
fn
The method of being buriedeventId
The buried point methodeventId
Buries the incoming method and returns the bury-finished method.
tracked
The Action burying event is triggered immediately
function tracked(eventId: string) :void;
Copy the code
eventId
ID of the buried event
trackApi
Buried listening to Axios
function trackApi(axiosInstance: AxiosInstance) :void;
Copy the code
onBury
Callback function when the buried time is triggered
function onBury(callback: (value: BuryCallBackPayload) => void) :void;
Copy the code
callback
The callback function
BuryCallBackPayload
interface BuryCallBackPayload {
type: "Action" | "Click" | "Leave" | "Enter" | "Api"; payload: BuryConfig; extra? : | Payload.ActionPayload | Payload.ApiPayload | Payload.ClickPayload | Payload.LoadPayload | Payload.RoutePayload; }Copy the code
type
The types are buried event, click, off page, load page, and interfacepayload
Load, in addition to the predefined configurationEnter
pageUrl
Page enteredurl
Leave
PageStayTime
The time spent on the current pagepageUrl
Off pageurl
Api
apiUrl
Of the interfaceurl
extra
Check the load of listening events for detailsGithub.com/darkXmo/mon…
help
How is it used in the Nuxt2 project
plugins
Create the bury.js or bury.ts file in the plugins folder.
// bury.js
import { init, initUrlMap } from '@xmon/bury';
const bury = init({
version: 'projectVersion'.dataPointVersion: 'v1'.project: 'projectName'
});
initUrlMap([{
path: "/".enter: "EnterEventPoint".leave: "LeaveEventPoint"},... ] ) bury.spy(); bury.onBury((value) = > {
// do something with value
})
Copy the code
Add plug-in configuration in nuxt.config.js or nuxt.config.ts
{
plugins: [{...src: "@/plugins/bury.ts".mode: 'client'},... ] ,}Copy the code
TODO
🚀 completed
The matters | state |
---|---|
addtracked Syntax sugar when runtracked() , the buried event is triggered without the need for separate encapsulation of the behavior |
🚀 |
Add configuration to optionally turn off global click event listening | 📝 |
Add configuration to enable global click event listening based on the page | 📝 |
If no page route to be monitored is detected, route monitoring is disabled | 📝 |
You can enable the Listening page Web indicator. For details, see Web-Vitals | 📝 |
You can enable the listening page Error event | 📝 |
Some of the defaults in items can be configured to speed up the creation of buried instances (e.g. IP + cityName, userId) | 📝 |