@wangofnextdoor/zzd-config
Version:
浙政钉配置和流量分析工具包
228 lines (227 loc) • 7.78 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.initFlowAnalysis = exports.sendPageView = exports.setUserInfo = void 0;
const zzd_1 = require("./config/zzd");
// DOM 兼容性补丁
const addDOMCompatibilityPatch = () => {
if (typeof Element === 'undefined')
return;
// 确保 DOM 原型链上有 hasAttribute 方法
if (Element.prototype && !Element.prototype.hasAttribute) {
Element.prototype.hasAttribute = function (name) {
return this.getAttribute(name) !== null;
};
}
// 为可能缺失的其他方法添加补丁
if (Element.prototype) {
if (!Element.prototype.getAttribute) {
Element.prototype.getAttribute = function (name) {
const attr = this.attributes && this.attributes[name];
return attr ? attr.value : null;
};
}
}
};
// 加载SDK脚本
const loadAnalysisScript = () => {
return new Promise((resolve, reject) => {
try {
if (typeof document === 'undefined') {
reject(new Error('Document is not available'));
return;
}
// 在加载脚本前先应用DOM兼容性补丁
addDOMCompatibilityPatch();
const script = document.createElement('script');
script.async = true;
script.id = 'beacon-aplus';
script.src = 'https://alidt.alicdn.com/alilog/mlog/aplus_cloud.js';
script.onload = () => {
console.log('流量分析SDK加载成功');
resolve();
};
script.onerror = (err) => {
console.error('流量分析SDK加载失败:', err);
reject(err);
};
const firstScript = document.getElementsByTagName('script')[0];
if (firstScript && firstScript.parentNode) {
firstScript.parentNode.insertBefore(script, firstScript);
}
else {
document.head.appendChild(script);
}
// 初始化全局队列
if (typeof window !== 'undefined') {
window.aplus_queue = window.aplus_queue || [];
}
}
catch (err) {
console.error('加载流量分析脚本时发生错误:', err);
reject(err);
}
});
};
// 基础配置
const initBaseConfig = () => {
try {
if (typeof window === 'undefined' || !window.aplus_queue)
return;
const aplus_queue = window.aplus_queue;
// 设置日志服务器地址
aplus_queue.push({
action: 'aplus.setMetaInfo',
arguments: ['aplus-rhost-v', 'alog-api.ding.zj.gov.cn'],
});
aplus_queue.push({
action: 'aplus.setMetaInfo',
arguments: ['aplus-rhost-g', 'alog-api.ding.zj.gov.cn'],
});
// 设置 AppID
const u = navigator.userAgent;
const isAndroid = u.indexOf('Android') > -1;
const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
aplus_queue.push({
action: 'aplus.setMetaInfo',
arguments: [
'appId',
isAndroid ? '28302650' : isIOS ? '28328447' : '47130293',
],
});
}
catch (err) {
console.error('初始化基础配置时发生错误:', err);
}
};
/**
* 设置用户信息
* @param userId 用户ID
* @param deviceId 设备ID(可选)
*/
const setUserInfo = (userId, deviceId) => {
try {
if (typeof window === 'undefined' || !window.aplus_queue)
return;
const aplus_queue = window.aplus_queue;
// 开始阻塞日志发送,等待用户信息设置完成
aplus_queue.push({
action: 'aplus.setMetaInfo',
arguments: ['_hold', 'BLOCK'],
});
// 设置用户ID
if (userId) {
aplus_queue.push({
action: 'aplus.setMetaInfo',
arguments: ['_user_id', userId],
});
}
// 设置设备ID(可选)
if (deviceId) {
aplus_queue.push({
action: 'aplus.setMetaInfo',
arguments: ['_dev_id', deviceId],
});
}
// 恢复日志发送,此时阻塞的日志会携带上用户信息发出
aplus_queue.push({
action: 'aplus.setMetaInfo',
arguments: ['_hold', 'START'],
});
}
catch (err) {
console.error('设置用户信息时发生错误:', err);
}
};
exports.setUserInfo = setUserInfo;
/**
* 发送页面浏览埋点
* @param params 页面参数
*/
const sendPageView = (params) => {
try {
if (typeof window === 'undefined' || !window.aplus_queue)
return;
const aplus_queue = window.aplus_queue;
// 开始阻塞日志发送
aplus_queue.push({
action: 'aplus.setMetaInfo',
arguments: ['_hold', 'BLOCK'],
});
// 单页应用需要设置等待手动发送PV
aplus_queue.push({
action: 'aplus.setMetaInfo',
arguments: ['aplus-waiting', 'MAN'],
});
// 合并配置和用户传入的参数
const mergedParams = {
...(0, zzd_1.getAppConfig)(),
page_url: typeof window !== 'undefined' ? window.location.href : '',
...params, // 用户传入的参数会覆盖默认值
};
// 发送PV日志
aplus_queue.push({
action: 'aplus.sendPV',
arguments: [{ is_auto: false }, mergedParams],
});
// 恢复日志发送
aplus_queue.push({
action: 'aplus.setMetaInfo',
arguments: ['_hold', 'START'],
});
console.log("sendPageView", JSON.stringify(mergedParams));
}
catch (err) {
console.error('发送页面浏览埋点时发生错误:', err);
}
};
exports.sendPageView = sendPageView;
// 检查环境是否支持流量分析
const isSupportedEnvironment = () => {
try {
return typeof document !== 'undefined' &&
typeof Element !== 'undefined' &&
typeof window !== 'undefined';
}
catch (_a) {
return false;
}
};
/**
* 初始化流量分析
* @returns 是否初始化成功
*/
const initFlowAnalysis = async () => {
try {
// 检查环境支持
if (!isSupportedEnvironment()) {
console.warn('当前环境不支持流量分析SDK');
return false;
}
// 添加全局错误处理
if (typeof window !== 'undefined') {
const originalError = window.onerror;
window.onerror = function (message, source, lineno, colno, error) {
// 如果是来自 aplus_cloud.js 的错误,记录但不阻止程序运行
if (source && source.includes('aplus_cloud.js')) {
console.warn('流量分析SDK出现错误,但不影响主程序运行:', message);
return true; // 阻止错误冒泡
}
// 其他错误继续处理
if (originalError) {
return originalError.call(this, message, source, lineno, colno, error);
}
return false;
};
}
await loadAnalysisScript();
// 等待一小段时间确保脚本完全加载
await new Promise(resolve => setTimeout(resolve, 100));
initBaseConfig();
return true;
}
catch (err) {
console.error('流量分析SDK初始化失败', err);
return false;
}
};
exports.initFlowAnalysis = initFlowAnalysis;