如何在一个网页上放置多个Facebook跟踪像素?

9
我们正在尝试使用Facebook的广告跟踪像素来跟踪广告。我们查看了Facebook的文档,但并没有找到解决办法。
我需要知道如何在一个页面上触发多个Facebook像素,因为我们有多个广告正在运行。
我获取了每个像素的代码,并将其放置在页面上,然后我们有一个购物车页面,在其中触发或添加“购买”事件。但由于我已经将脚本复制了3次,它似乎会触发3次。我希望它只能针对每个像素触发一次。
这是我目前所拥有的:
<!-- Facebook Pixel Code - Ad 1-->
 <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','//connect.facebook.net/en_US/fbevents.js');

 fbq('init', 'xxxxxxxxxxxxx12');
 fbq('track', "PageView");
 // Purchase
 // Track purchases or checkout flow completions (ex. landing on "Thank You" or confirmation page)
 fbq('track', 'Purchase', {value: '1.00', currency: 'USD'});
 </script>
 <noscript><img height="1" width="1" style="display:none"
 src="https://www.facebook.com/tr?id=xxxxxxxxxxxxx12&ev=PageView&noscript=1"
  /></noscript>
<!-- End Facebook Pixel Code -->

 <!-- Facebook Pixel Code - Ad 2-->
 <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','//connect.facebook.net/en_US/fbevents.js');

 fbq('init', 'xxxxxxxxxxxxx34');
 fbq('track', "PageView");
 // Purchase
 // Track purchases or checkout flow completions (ex. landing on "Thank You" or confirmation page)
 fbq('track', 'Purchase', {value: '1.00', currency: 'USD'});

 </script>
 <noscript><img height="1" width="1" style="display:none"
 src="https://www.facebook.com/tr?id=xxxxxxxxxxxxx34&ev=PageView&noscript=1"
  /></noscript>
<!-- End Facebook Pixel Code -->

 <!-- Facebook Pixel Code - Ad 2-->
 <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','//connect.facebook.net/en_US/fbevents.js');

 fbq('init', 'xxxxxxxxxxxxx56');
 fbq('track', "PageView");
 // Purchase
 // Track purchases or checkout flow completions (ex. landing on "Thank You" or confirmation page)
 fbq('track', 'Purchase', {value: '1.00', currency: 'USD'});
 </script>
 <noscript><img height="1" width="1" style="display:none"
 src="https://www.facebook.com/tr?id=xxxxxxxxxxxxx56&ev=PageView&noscript=1"
  /></noscript>
<!-- End Facebook Pixel Code -->

这样做对吗?还是我需要采取不同的方法,以使购买事件不会触发4次。我正在使用Chrome的FB Pixel Helper插件来确保所有像素都能正常运行,但是我收到了多次触发的错误。

我应该这样做吗?

 <!-- Facebook Pixel Code - ALL ADS-->
 <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','//connect.facebook.net/en_US/fbevents.js');

 fbq('init', 'xxxxxxxxxxxxx12');
 fbq('init', 'xxxxxxxxxxxxx34');
 fbq('init', 'xxxxxxxxxxxxx56');
 fbq('track', "PageView");
 // Purchase
 // Track purchases or checkout flow completions (ex. landing on "Thank You" or confirmation page)
 fbq('track', 'Purchase', {value: '1.00', currency: 'USD'});
 </script>
 <noscript><img height="1" width="1" style="display:none"
 src="https://www.facebook.com/tr?id=xxxxxxxxxxxxx12&ev=PageView&noscript=1"
  /></noscript>
<!-- End Facebook Pixel Code -->

我刚刚试了一下,使用多个init调用,看起来它正在工作(Chrome助手中没有错误),但是当客户确认时,我稍后会在这里更新! - joshangell
1
你解决了吗? - benjah
8个回答

16

我曾经遇到同样的问题,但是我无法在任何地方找到解决方法。后来我仔细研究了代码,发现有一个名为 "addPixelId" 的可用方法。在我的测试中,您可以在 "init" 后立即使用它,这将添加第二个 ID。您跟踪的任何事件现在都会发送到这两个 ID。例如:

fbq('init', 'xxxxxxxxxxxxx12');
fbq('addPixelId', 'xxxxxxxxxxxxx34');
fbq('addPixelId', 'xxxxxxxxxxxxx56');
fbq('track', 'PageView');

需要注意的另一件事就是,你跟踪的任何事件都将对你定义的所有ID进行跟踪。 对我来说一切都非常完美,没有任何问题。


2
源代码显示,initaddPixelId方法实际上是在做同样的事情。使用addPixelId的缺点是会收到警告“检测到具有冲突版本的多个像素”。我想Facebook正在试图弃用这种方法,所以最好采用OP建议的解决方案。 - Aaron Blenkush
@AaronBlenkush — 在本评论发布时,同时使用initaddPixelId时会出现该警告。 - Matvey Andreyev
9
没错,你不需要使用 addPixelId。只需使用 init 即可。 - Aaron Blenkush

5
只需在一个JS文件中输入以下代码即可: //Facebook Multi-Pixel
    (function() {
        var fbq = (function() {
            function fbq()
            {
                if(arguments.length > 0) {
                    var action, pixel_id, type_track, content_obj;

                if( typeof arguments[0] == "string") action = arguments[0];
                if( typeof arguments[1] == "string") pixel_id = arguments[1];
                if( typeof arguments[2] == "string") type_track = arguments[2];
                if( typeof arguments[3] == "object") content_obj = arguments[3];

                var params = [];
                if(typeof action == "string" && action.replace(/\s+/gi, "") != "" && 
                   typeof pixel_id == "string" && pixel_id.replace(/\s+/gi, "") != "" &&
                   typeof type_track == "string" && type_track.replace(/\s+/gi, "")) {

                    params.push("id=" + encodeURIComponent(pixel_id));
                    switch(type_track) {
                        case "PageView":
                        case "ViewContent":
                        case "Search":
                        case "AddToCart":
                        case "InitiateCheckout":
                        case "AddPaymentInfo":
                        case "Lead":
                        case "CompleteRegistration":
                        case "Purchase":
                        case "AddToWishlist":
                            params.push("ev=" + encodeURIComponent(type_track));
                            break;
                        default:
                            return;
                    }

                    params.push("dl=" + encodeURIComponent(document.location.href));
                    params.push("rl=" + encodeURIComponent(document.referrer));
                    params.push("if=false");
                    params.push("ts=" + new Date().getTime());

                    if(typeof content_obj == "object") {
                        for(var u in content_obj) {
                            if(typeof content_obj[u] == "object" && content_obj[u] instanceof Array) {
                                if(content_obj[u].length > 0) {
                                    for(var y=0; y<content_obj[u].length; y++) { content_obj[u][y] = (content_obj[u][y]+"").replace(/^\s+|\s+$/gi, "").replace(/\s+/gi," ").replace(/,/gi, "§"); }
                                    params.push("cd[" + u + "]=" + encodeURIComponent(content_obj[u].join(",").replace(/^/gi, "[\"").replace(/$/gi, "\"]").replace(/,/gi, "\",\"").replace(/§/gi, "\,")));
                                }
                            }
                            else if(typeof content_obj[u] == "string")
                                params.push("cd[" + u + "]=" + encodeURIComponent(content_obj[u]));
                        }
                    }

                    params.push("v=" + encodeURIComponent("2.5.0"));                                

                    if(typeof window.jQuery == "function") {
                        var iframe_id = new Date().getTime();
                        jQuery("body").append("<img height='1' width='1' style='display:none;width:1px;height:1px;' id='fb_" + iframe_id + "' src='https://www.facebook.com/tr/?" + params.join("&") + "' />");
                        setTimeout(function() { jQuery("#fb_" + iframe_id).remove(); }, 1000);
                    }




                }


            }
        }

    return fbq;
    });

window.fbq = new fbq();
})();

而且,以下是使用示例:
fbq('track', "<PIXEL_ID>", "PageView");

fbq('track", "<PIXEL_ID>", "ViewContent", {
                 content_name: "name test",
                 content_category: "category test",
                 content_ids: ["test"],
                 content_type: "product",
                 value: 7.99,
                 currency: "GBP"
          });

等等。


4

根据Facebook源代码(基于https://developers.facebook.com/),我建议采用当前的工作方法。多次使用“init”函数,非常简单...

<!-- Facebook Pixel Code -->
<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');
fbq('init', '158xxxxxxxxxx911');
fbq('init', '180xxxxxxxxxx762');
fbq('init', '125xxxxxxxxxx694');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=180xxxxxxxxxx762&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->

你能引用一下 Facebook 推荐的来源吗? - Thang Pham
1
@ThangPham,我的上一个回答有误导之嫌。我无法找到Facebook推荐在一个页面中进行多像素跟踪的任何方法。因此,我基于Facebook的源代码设计了这种代码方法,并已经在自己的多像素环境中证明其有效。 - Marty McGee
1
这种代码方法是由 Facebook 开发团队使用的,可以通过查看此处的页面源代码进行参考:https://developers.facebook.com/ --请注意他们仅使用1个img像素--而不是多个图像。 - Marty McGee

2

如果您只想跟踪特定像素ID的某些事件,另一种解决方案是仅使用无JavaScript方法。

您可以在其文档中查看一些示例:https://developers.facebook.com/docs/facebook-pixel/api-reference

<img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=FB_PIXEL_ID&amp;ev=MyCustomEvent&amp;cd[custom_param]=custom_value"
/>

<img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=FB_PIXEL_ID&amp;ev=PageView&amp;noscript=1"
/>

您只需要正确格式化参数即可。


2
问题在于Facebook像素代码/初始化需要一点时间来加载,更不用说用户的连接和设备也会影响初始化时间。
您不希望将代码粘贴三次。
首先调用核心FB JS像素代码,引用库。
!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');

然后创建您的像素ID数组。
// Array of FB PixelIDs
var pixel_ids = ['xxx111','xxx222'];

遍历数组,并在每个像素初始化时添加一些小的延迟。您可以根据需要进行微调。您需要使用闭包函数来确保正确的数组值被分配。

// Iterate over the ids and ensure each one is initialized
for (var i = 1; i <= pixel_ids.length; i++){
  // Add delay here to allow each pixel to instantiate
  setTimeout(function(x) { return function() {fbq('init',x.toString());};
    }(pixel_ids[i-1]), 33*i);
}

现在是时候调用你实际的跟踪事件,同时延迟以确保它们在像素初始化后被触发。
setTimeout(function() { fbq('track', "PageView");}, (33*pixel_ids.length)+33);
setTimeout(function() { fbq('track', 'Purchase', {value: '1.00', currency: 'USD'});},(33*pixel_ids.length)+66);

为了更好的效果,每个像素都需要放置一个HTML no script调用PageView
<noscript><img height="1" width="1" style="display:none"   
src="https://www.facebook.com/tr?id=xxx111&ev=PageView&noscript=1"/>
</noscript>
<noscript><img height="1" width="1" style="display:none"   
src="https://www.facebook.com/tr?id=xxx2222&ev=PageView&noscript=1"/>
</noscript>

触发的事件数量应该等于您拥有的像素数乘以事件的数量(即每个像素注册的每个事件)...如果您正确实现,就不应该出现错误。


2
超时不是必要的。Facebook的代码是异步的,这意味着一旦您创建了fbq函数(添加到页面的代码),无论Facebook JS代码是否已加载都没有关系。如果代码尚未加载,则将项目推送到数组中,一旦代码加载,它将解析数组,然后代码将立即执行。这类似于Google Analytics的工作方式。 - Adam Haining

2
@ClosDesign,你走在正确的轨道上了!正如你所怀疑的那样,您可以多次调用 fbq('init', '[your-pixel-id]'),这将把每个像素ID添加到所有事件将被跟踪的ID列表中。我写了一篇博客文章关于在一个网站上使用多个Facebook像素的问题,因此请在那里阅读更多详细信息。
使用您的示例代码,首先要包含Facebook的JavaScript像素代码。这将加载来自Facebook的JavaScript,这是发送像素事件所需的fbq对象:
!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','//connect.facebook.net/en_US/fbevents.js');

然后,是时候初始化所有像素ID了:init
fbq('init', 'xxxxxxxxxxxxx12');
fbq('init', 'xxxxxxxxxxxxx34');
fbq('init', 'xxxxxxxxxxxxx56');

一旦您使用fbq('init')初始化了站点上的所有像素ID,请使用Facebook像素助手确认所有像素已加载。 您还可以通过在JavaScript控制台中运行以下代码来手动确认它们已加载:
fbq.getState().pixels

之后,您对事件进行跟踪的任何调用都将被跟踪到您在上面初始化的所有像素 ID。因此,如果您调用:
fbq('track', "PageView");

所有三个像素都将向Facebook发送PageView事件。您的Purchase事件也是同样的方式。
至于Facebook包含的<noscript>标签,您需要在站点上调用每个像素ID的<img>标签:
<noscript>
    <img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=xxxxxxxxxxxxx12&ev=PageView&noscript=1" />
    <img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=xxxxxxxxxxxxx34&ev=PageView&noscript=1" />
    <img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=xxxxxxxxxxxxx56&ev=PageView&noscript=1" />
</noscript>

请注意,如果用户关闭了JavaScript,则那些<img>标签只会向Facebook发送一个请求来跟踪PageView事件。除非您为每个像素ID创建另一个<img>标签并指定跟踪Purchase事件的数据,否则将不会跟踪Purchase事件。
一个自然的后续问题是,“我能仅跟踪到我的站点上初始化的多个像素中的一个吗?” 不可以使用Facebook的fbq对象。
然而,有一种解决方法workaround。使用上面的<img>标签方法,您可以向Facebook发送事件,并仅将事件跟踪到一个像素ID。此方法完全绕过了fbq对象,并动态构建了一个包含您指定的事件信息的<img>标签。

代码

(function (window, document) {
    if (window.myfbq) return;
    window.myfbq = (function () {
        if (arguments.length > 0) {
            var pixelId, trackType, contentObj;

            if (typeof arguments[0] == 'string') pixelId = arguments[0];
            if (typeof arguments[1] == 'string') trackType = arguments[1];
            if (typeof arguments[2] == 'object') contentObj = arguments[2];

            var params = [];
            if (typeof pixelId === 'string' && pixelId.replace(/\s+/gi, '') != '' &&
            typeof trackType === 'string' && trackType.replace(/\s+/gi, '')) {
                params.push('id=' + encodeURIComponent(pixelId));
                switch (trackType) {
                    case 'PageView':
                    case 'ViewContent':
                    case 'Search':
                    case 'AddToCart':
                    case 'InitiateCheckout':
                    case 'AddPaymentInfo':
                    case 'Lead':
                    case 'CompleteRegistration':
                    case 'Purchase':
                    case 'AddToWishlist':
                        params.push('ev=' + encodeURIComponent(trackType));
                        break;
                    default:
                        return;
                }

                params.push('dl=' + encodeURIComponent(document.location.href));
                if (document.referrer) params.push('rl=' + encodeURIComponent(document.referrer));
                params.push('if=false');
                params.push('ts=' + new Date().getTime());

                if (typeof contentObj == 'object') {
                    for (var u in contentObj) {
                        if (typeof contentObj[u] == 'object' && contentObj[u] instanceof Array) {
                            if (contentObj[u].length > 0) {
                                for (var y = 0; y < contentObj[u].length; y++) { contentObj[u][y] = (contentObj[u][y] + '').replace(/^\s+|\s+$/gi, '').replace(/\s+/gi, ' ').replace(/,/gi, '§'); }
                                params.push('cd[' + u + ']=' + encodeURIComponent(contentObj[u].join(',').replace(/^/gi, '[\'').replace(/$/gi, '\']').replace(/,/gi, '\',\'').replace(/§/gi, '\,')));
                            }
                        }
                        else if (typeof contentObj[u] == 'string')
                            params.push('cd[' + u + ']=' + encodeURIComponent(contentObj[u]));
                    }
                }

                params.push('v=' + encodeURIComponent('2.7.19'));

                var imgId = new Date().getTime();
                var img = document.createElement('img');
                img.id = 'fb_' + imgId, img.src = 'https://www.facebook.com/tr/?' + params.join('&'), img.width = 1, img.height = 1, img.style = 'display:none;';
                document.body.appendChild(img);
                window.setTimeout(function () { var t = document.getElementById('fb_' + imgId); t.parentElement.removeChild(t); }, 1000);
            }
        }
    });
})(window, document);

使用方法

myfbq("[your-pixel-id]", "PageView");
myfbq("[your-pixel-id]", "ViewContent");
myfbq("[your-pixel-id]", "ViewContent", { content_type: "product", content_ids: ['892185001003'] });

嗨。我知道这个问题已经过去一段时间了,但是这行代码中的2.7.19是什么意思? params.push('v=' + encodeURIComponent('2.7.19')); 我猜它是一个版本号,但是针对什么呢?如果我想使用Facebook的最新更新,我应该使用最新版本吗?你有什么猜测吗? - Nestor Villalobos
@NestorVillalobos 正确。该参数指定了版本号。在我编写脚本之前,从 fbq 事件中观察到的版本号是 2.7.19,所以我在脚本中指定了这个版本号。如果您看到了更新的版本号,则可以自行尝试。但是,如果它们在 2.7.19 之后更改了功能,您可能需要添加一些现在所需的其他属性之类的内容。 - John Washam

1

0

想提供使用页面上多个像素的最新链接,链接如下:https://developers.facebook.com/docs/facebook-pixel/advanced#multipixels

以下是代码示例:

fbq('init', '<PIXEL_A>');
fbq('init', '<PIXEL_B>');
fbq('track', 'PageView'); //fire PageView for both initialized pixels

// only fire the Purchase event for Pixel A
fbq('trackSingle', '<PIXEL_A>', 'Purchase', {
      value: 4,
      currency: 'GBP',
});

// only fire the custom event Step4 for Pixel B
fbq('trackSingleCustom', '<PIXEL_B>', 'Step4',{
  //optional parameters
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接