# UNiAPP中使用facebook埋点
# evalJS
只能在 nvue 中使用
class FacebookPixelManager {
constructor() {
this.isInitialized = false
this.pixelWebView = null
this.pixelId = null
this.platform = uni.getSystemInfoSync().platform
}
// 初始化
async init(pixelId) {
if (!pixelId) {
console.error('Facebook Pixel ID is required')
return false
}
this.pixelId = pixelId
// #ifdef H5
await this.initH5(pixelId)
// #endif
// #ifdef APP-PLUS
await this.initApp(pixelId)
// #endif
this.isInitialized = true
console.log('Facebook Pixel 初始化完成')
return true
}
// H5 初始化
initH5(pixelId) {
return new Promise((resolve, reject) => {
// 检查是否已存在 Facebook Pixel
if (typeof window !== 'undefined' && window.fbq) {
console.log('Facebook Pixel 已经存在')
resolve()
return
}
const script = document.createElement('script')
script.onload = () => {
try {
window.fbq('init', pixelId)
window.fbq('track', 'PageView')
resolve()
} catch (e) {
console.error('Facebook Pixel 初始化失败:', e)
reject(e)
}
}
script.onerror = (e) => {
console.error('Facebook Pixel 脚本加载失败:', e)
reject(e)
}
script.src = 'https://connect.facebook.net/en_US/fbevents.js'
document.head.appendChild(script)
})
}
// App 初始化
async initApp(pixelId) {
// 创建隐藏的 WebView 来承载 Facebook Pixel
return new Promise((resolve) => {
// 确保 plus 环境可用
if (typeof plus !== 'undefined') {
this.createHiddenWebView(pixelId, resolve)
} else {
// 如果 plus 不可用,使用延迟方式
setTimeout(() => {
if (typeof plus !== 'undefined') {
this.createHiddenWebView(pixelId, resolve)
} else {
console.warn('Plus environment not available, Facebook Pixel may not work in app')
resolve()
}
}, 1000)
}
})
}
// 创建隐藏的 WebView
createHiddenWebView(pixelId, callback) {
try {
// 确保 plus 环境可用
if (typeof plus === 'undefined') {
console.warn('Plus environment not available')
if (callback) callback()
return
}
// 检查是否已经创建了 WebView
if (this.pixelWebView) {
try {
plus.webview.close(this.pixelWebView)
} catch(e) {
console.warn('关闭旧的 Pixel WebView 失败:', e)
}
}
// 创建包含 Facebook Pixel 的 HTML 内容
const htmlContent = encodeURIComponent(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Facebook Pixel Bridge</title>
</head>
<body>
<script>
!function(f,b,e,v,n,t,s){
if(f.fbq)return;n=f.fbq=function(){
n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)
};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)
}(window, document,'script','https://connect.facebook.net/en_US/fbevents.js');
// 初始化 Pixel
fbq('init', '${pixelId}');
fbq('track', 'PageView');
// 创建桥接方法
window.PixelBridge = {
track: function(event, params) {
try {
fbq('track', event, params || {});
return { success: true, message: 'Event tracked successfully' };
} catch(e) {
return { success: false, message: e.message };
}
},
trackSingle: function(pixelId, event, params) {
try {
fbq('trackSingle', pixelId, event, params || {});
return { success: true, message: 'Event tracked successfully' };
} catch(e) {
return { success: false, message: e.message };
}
},
getData: function() {
return { initialized: true, pixelId: '${pixelId}' };
}
};
// 通知父页面初始化完成
if (window.plus) {
plus.webview.postMessageToNWeb({
action: 'pixelInitialized',
pixelId: '${pixelId}'
});
}
</script>
</body>
</html>
`)
const webViewUrl = `data:text/html;charset=utf-8,${htmlContent}`
this.pixelWebView = plus.webview.create(
webViewUrl,
'facebook-pixel-webview',
{
width: '1px',
height: '1px',
left: '-1000px',
top: '-1000px',
opacity: 0.01,
hardwareAccelerated: true,
bounce: 'none',
bounceBackground: '#ffffff',
render: 'always'
}
)
// 监听 WebView 事件
this.pixelWebView.addEventListener('loaded', () => {
console.log('Facebook Pixel WebView 加载完成')
if (callback) callback()
})
this.pixelWebView.addEventListener('error', (error) => {
console.error('Facebook Pixel WebView 加载失败:', error)
if (callback) callback()
})
// 监听来自 WebView 的消息
this.pixelWebView.addEventListener('message', (msg) => {
console.log('收到 WebView 消息:', msg)
})
// 显示 WebView(隐藏状态下)
this.pixelWebView.show('none', 0)
} catch (error) {
console.error('创建 Facebook Pixel WebView 失败:', error)
if (callback) callback()
}
}
// 跟踪事件
track(eventName, parameters = {}) {
if (!this.isInitialized) {
console.warn('Facebook Pixel 未初始化')
return Promise.resolve(false)
}
// #ifdef H5
if (typeof window !== 'undefined' && window.fbq) {
try {
window.fbq('track', eventName, parameters)
console.log(`H5 - Facebook Pixel 事件 "${eventName}" 发送成功`, parameters)
return Promise.resolve(true)
} catch (e) {
console.error('H5 - Facebook Pixel 事件发送失败:', e)
return Promise.resolve(false)
}
}
// #endif
// #ifdef APP-PLUS
if (this.pixelWebView && typeof plus !== 'undefined') {
return new Promise((resolve) => {
try {
const jsCode = `
try {
if (window.PixelBridge && typeof window.PixelBridge.track === 'function') {
window.PixelBridge.track('${eventName}', ${JSON.stringify(parameters || {})});
} else {
fbq('track', '${eventName}', ${JSON.stringify(parameters || {})});
}
({ success: true, message: 'Event sent' });
} catch(e) {
({ success: false, message: e.message });
}
`
this.pixelWebView.evalJS(jsCode, (result) => {
const success = result && (result.success === true || result.indexOf('success') > -1)
console.log(`App - Facebook Pixel 事件 "${eventName}" 发送${success ? '成功' : '失败'}`, parameters)
resolve(success)
})
} catch (e) {
console.error('App - Facebook Pixel 事件发送失败:', e)
resolve(false)
}
})
}
// #endif
console.warn('Facebook Pixel 不可用的环境')
return Promise.resolve(false)
}
// 跟踪自定义事件
trackCustom(eventName, parameters = {}) {
if (!this.isInitialized) {
console.warn('Facebook Pixel 未初始化')
return Promise.resolve(false)
}
// #ifdef H5
if (typeof window !== 'undefined' && window.fbq) {
try {
window.fbq('trackCustom', eventName, parameters)
console.log(`H5 - Facebook Pixel 自定义事件 "${eventName}" 发送成功`, parameters)
return Promise.resolve(true)
} catch (e) {
console.error('H5 - Facebook Pixel 自定义事件发送失败:', e)
return Promise.resolve(false)
}
}
// #endif
// #ifdef APP-PLUS
if (this.pixelWebView && typeof plus !== 'undefined') {
return new Promise((resolve) => {
const jsCode = `
try {
fbq('trackCustom', '${eventName}', ${JSON.stringify(parameters || {})});
({ success: true, message: 'Custom event sent' });
} catch(e) {
({ success: false, message: e.message });
}
`
this.pixelWebView.evalJS(jsCode, (result) => {
const success = result && result.success === true
console.log(`App - Facebook Pixel 自定义事件 "${eventName}" 发送${success ? '成功' : '失败'}`)
resolve(success)
})
})
}
// #endif
return Promise.resolve(false)
}
// 常用事件快捷方法
trackPageView() {
return this.track('PageView')
}
trackViewContent(contentData) {
return this.track('ViewContent', contentData)
}
trackAddToCart(cartData) {
return this.track('AddToCart', cartData)
}
trackPurchase(purchaseData) {
return this.track('Purchase', purchaseData)
}
trackInitiateCheckout(checkoutData) {
return this.track('InitiateCheckout', checkoutData)
}
trackAddPaymentInfo(paymentData) {
return this.track('AddPaymentInfo', paymentData)
}
trackCompleteRegistration(registrationData) {
return this.track('CompleteRegistration', registrationData)
}
// 销毁资源
destroy() {
if (this.pixelWebView && typeof plus !== 'undefined') {
try {
plus.webview.close(this.pixelWebView)
this.pixelWebView = null
} catch (e) {
console.error('销毁 Facebook Pixel WebView 失败:', e)
}
}
this.isInitialized = false
console.log('Facebook Pixel 资源已销毁')
}
}
// 单例模式导出
export const facebookPixel = new FacebookPixelManager()
// 便捷导出方法
export default {
init: (pixelId) => facebookPixel.init(pixelId),
track: (eventName, parameters) => facebookPixel.track(eventName, parameters),
trackCustom: (eventName, parameters) => facebookPixel.trackCustom(eventName, parameters),
trackPageView: () => facebookPixel.trackPageView(),
trackViewContent: (data) => facebookPixel.trackViewContent(data),
trackAddToCart: (data) => facebookPixel.trackAddToCart(data),
trackPurchase: (data) => facebookPixel.trackPurchase(data),
trackInitiateCheckout: (data) => facebookPixel.trackInitiateCheckout(data),
trackAddPaymentInfo: (data) => facebookPixel.trackAddPaymentInfo(data),
trackCompleteRegistration: (data) => facebookPixel.trackCompleteRegistration(data),
destroy: () => facebookPixel.destroy()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# renderjs
只能在 vue 页面使用
<!-- components/FacebookPixel.vue -->
<template>
<view style="display: none">
<view :prop="eventData" :change:prop="fbPixel.processEvent"></view>
</view>
</template>
<script>
export default {
name: 'FacebookPixel',
props: {
pixelId: {
type: String,
required: true,
},
},
data() {
return {
eventData: null,
// 添加初始化状态标记
isInitializing: false,
};
},
methods: {
track(eventName, parameters = {}) {
// 避免重复初始化
if (this.isInitializing) {
console.log('正在初始化中,跳过事件跟踪');
return;
}
this.eventData = {
type: 'track',
eventName,
parameters,
pixelId: this.pixelId,
timestamp: Date.now(),
};
},
onEventTracked(result) {
console.log('事件回调:', result);
},
},
};
</script>
<script module="fbPixel" lang="renderjs">
export default {
data() {
return {
currentPixelId: '',
initialized: false,
// 添加初始化锁
isInitializing: false
}
},
methods: {
processEvent(newVal, oldVal, ownerVm, vm) {
if (newVal && newVal.type === 'track' && newVal.eventName) {
// 避免重复初始化
if (this.isInitializing) {
console.log('RenderJS 正在初始化中...');
return;
}
// 更新 pixelId
if (newVal.pixelId && newVal.pixelId !== this.currentPixelId) {
this.currentPixelId = newVal.pixelId;
this.initPixel(newVal.pixelId);
}
// 跟踪事件
this.trackEvent(newVal.eventName, newVal.parameters);
}
},
initPixel(pixelId) {
// 添加初始化锁,防止重复执行
if (this.initialized || this.isInitializing) {
console.log('Pixel 已初始化或正在初始化');
return;
}
console.log(this,'开始初始化 Facebook Pixel:', pixelId);
this.isInitializing = true;
window.fbq = window.fbq || function() {
(window.fbq.queue = window.fbq.queue || []).push(arguments);
};
window.fbq.push = window.fbq;
window.fbq.loaded = true;
window.fbq.version = '2.0';
window.fbq.queue = window.fbq.queue || [];
const script = document.createElement('script');
script.async = true;
script.defer = true;
script.src = 'https://connect.facebook.net/en_US/fbevents.js';
script.onload = () => {
try {
window.fbq('init', pixelId);
window.fbq('track', 'PageView');
this.initialized = true;
this.isInitializing = false; // 释放锁
console.log('Facebook Pixel 初始化完成');
} catch (e) {
console.error('Failed to initialize Facebook Pixel:', e);
this.isInitializing = false; // 释放锁
}
};
script.onerror = (e) => {
console.error('Facebook Pixel script load failed:', e);
this.isInitializing = false; // 释放锁
};
document.head.appendChild(script);
},
trackEvent(eventName, parameters) {
// 确保已初始化
if (!this.initialized && this.currentPixelId && !this.isInitializing) {
this.initPixel(this.currentPixelId);
return;
}
// 如果正在初始化,等待完成
if (this.isInitializing) {
setTimeout(() => {
this.trackEvent(eventName, parameters);
}, 100);
return;
}
try {
if (typeof window !== 'undefined' && window.fbq) {
window.fbq('track', eventName, parameters || {});
this.callMethod('onEventTracked', {
success: true,
event: eventName
});
console.log(`Facebook Pixel event "${eventName}" tracked`);
}
} catch (error) {
this.callMethod('onEventTracked', {
success: false,
error: error.message
});
console.error(`Failed to track event "${eventName}":`, error);
}
},
callMethod(methodName, data) {
this.$ownerInstance.callMethod(methodName, data);
}
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
使用
<template>
<facebook-pixel pixelId="1277609904185264" ref="facebookPixelRef"/>
</template>
<script>
// ...
this.$refs.facebookPixelRef.track('PageView');
// ...
</script>
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9