由于 OP @user2297550 说他的最终目标是在事件触发后重定向用户,我将解释如何做到这一点(没有超时或间隔)。以前的一些答案试图检测 Facebook 像素 <script> 何时完成加载,但这与确定实际事件何时完成触发不同。据推测,OP 想知道PageView 事件何时完成。这个解决方案并不适合每个用例,但如果我们没有在页面上发生太多其他事情,它就会非常简单。
为了 ping 他们的服务器并跟踪事件,Facebook 的代码创建了一个new Image() 并将其src 属性设置为https://www.facebook.com/tr/?id=XXXXXX&ev=PageView&{more parameters} 之类的东西。我通过检查跟踪库并找到了这个sendGET 函数发现了这一点:
this.sendGET = function(b, c, d) {
b.replaceEntry("rqm", "GET");
var f = b.toQueryString();
f = i(c, d) + "?" + f;
if (f.length < 2048) {
var g = new Image();
if (d != null) {
var h = a.getShouldProxy();
g.onerror = function() {
a.setShouldProxy(!0), h || e.sendGET(b, c, d)
}
}
g.src = f;
return !0
}
return !1
};
我们可以通过使用我们的重定向代码填充默认的Image.onload 回调来挂钩该图像加载。结果是这样的,可以直接放在标题中普通 Facebook 像素代码的上方:
OriginalImage = Image;
Image = function(){
let oi = new OriginalImage();
oi.onload = function() {
// if the image that loaded was indeed a Facebook pixel
// for a "PageView" event, redirect
if( this.src.indexOf( 'facebook.com/tr/?id=XXXXXX&ev=PageView' ) != -1 )
window.location = 'https://example.com/redirect-here';
};
return oi;
};
因此,一个完整的“绘制用户并重定向”页面可能如下所示:
<html>
<head>
<!-- Facebook Pixel Code -->
<script>
OriginalImage = Image;
Image = function(){
let oi = new OriginalImage();
oi.onload = function() {
// if the image that loaded was indeed a Facebook pixel
// for a "PageView" event, redirect
if( this.src.indexOf( 'facebook.com/tr/?id=XXXXXX&ev=PageView' ) != -1 )
window.location = 'https://example.com/redirect-here';
};
return oi;
};
!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');
fbq('init', 'XXXXXX');
fbq('track', 'PageView');
</script>
<noscript>
<img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=XXXXXX&ev=PageView&noscript=1"/>
</noscript>
<!-- End Facebook Pixel Code -->
</head>
<body></body>
</html>
当然,您可以跳过 Javascript,直接从 <noscript> 块加载图像并添加“onload”属性,如下所示:
<html>
<head>
<!-- Facebook Pixel Code -->
<img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=XXXXXX&ev=PageView&noscript=1"
onload="window.location = 'https://example.com/redirect-here';"/>
<!-- End Facebook Pixel Code -->
</head>
<body></body>
</html>
但我猜,普通图像跟踪会降低 Facebook 识别用户的能力。
此策略可能适用于您想要检测任意事件何时完成发送到 Facebook 的更通用的用例。但是为普通页面上的每个图像填充 onload 回调可能是不明智的。也知道 Facebook 可以随时更改他们的代码,从而破坏这一点。