javascript 触发 Facebook 转换像素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19261604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Firing the Facebook Conversion Pixel
提问by dataprointhemaking
I'm still pretty new to Javascript, but I was wondering what would be the best way to fire the Facebook conversion pixel (below) without actually loading a "confirmation"/"Thank You" page?
我对 Javascript 还是很陌生,但我想知道在不实际加载“确认”/“谢谢”页面的情况下触发 Facebook 转换像素(如下)的最佳方法是什么?
<script type="text/javascript">
var fb_param = {};
fb_param.pixel_id = 'XXXXXXXXXXX';
fb_param.value = '0.00';
fb_param.currency = 'USD';
(function(){
var fpw = document.createElement('script');
fpw.async = true;
fpw.src = '//connect.facebook.net/en_US/fp.js';
var ref = document.getElementsByTagName('script')[0];
ref.parentNode.insertBefore(fpw, ref);
})();
</script>
<noscript><img height="1" width="1" alt="" style="display:none"
src="https://www.facebook.com/offsite_event.php?id=XXXXXXXXXX&value=0&currency=USD" /></noscript>
Facebook says that we should plug this into our "Thank You pages" that visitors see after they convert (fill out a form, make a purchase, etc). However, some of our forms are popups or forms on sidebars next to content that we don't want readers to be directed away from by a confirmation page.
Facebook 表示,我们应该将其插入我们的“感谢页面”,访问者在转换(填写表格、购买等)后会看到这些页面。但是,我们的一些表单是弹出窗口或侧边栏上的表单,我们不希望确认页面将读者引开。
With Google Analytics, I can create an "invisible" pageview by firing _gaq.push(['_trackPageview']); code that can tell GA that it should count that invisible pageview as a goal completion.
使用 Google Analytics,我可以通过触发 _gaq.push(['_trackPageview']); 来创建“不可见”的综合浏览量;可以告诉 GA 应该将不可见的综合浏览量计为目标完成的代码。
Is there something similar to that that's general enough to tell my site to fire the FB pixel?
是否有类似的东西足以告诉我的网站触发 FB 像素?
采纳答案by Blexy
EDIT: I've updated my code as what I had mentioned previously did not work. Thanks to @Flambino to pointing out.
编辑:我已经更新了我的代码,因为我之前提到的不起作用。感谢@Flambino 指出。
This is my revised answer using a pixel rather than a script to pass the conversion pixel. I reference the How to track a Google Adwords conversion onclick?SO post:
这是我使用像素而不是脚本来传递转换像素的修订答案。我参考了如何在点击时跟踪 Google Adwords 转化?所以帖子:
<head>
<script type="text/javascript">
function facebookConversionPixel(fb_pixel, fb_value){
var image = new Image(1,1);
image.src = "//www.facebook.com/offsite_event.php?id=" + fb_pixel + "&value=" + fb_value + "&currency=USD";
}
</script>
</head>
<body>
<a href="#" onclick="facebookConversionPixel(123456,0.00);">FBCONV</a>
</body>
回答by Patrick Berkeley
From the FB docs "How to track in-page events":
来自 FB 文档“如何跟踪页内事件”:
After the base code snippet is installed, you can track in-page actions, such as clicks on a button, by making a _fbq.push('track') call for the conversion pixel through registering different event handlers on an HTML DOM element. For example:
安装基本代码片段后,您可以通过在 HTML DOM 元素上注册不同的事件处理程序来对转换像素发出 _fbq.push('track') 调用,从而跟踪页面内操作,例如单击按钮。例如:
function trackConversionEvent(val, cny) {
var cd = {};
cd.value = val;
cd.currency = cny;
_fbq.push(['track', '<pixel_id>', cd]);
}
<button onClick="trackConversionEvent('10.00','USD');" />
回答by Tallboy
Just move the entire original code into the event of your choice. Then just change 1 part of the code. The thing you will have to do is make the fb_param
global instead of local.
只需将整个原始代码移动到您选择的事件中即可。然后只需更改代码的 1 部分。您必须做的是使fb_param
全局而不是本地。
See below at the comment
见下方评论
$('.button').click(function() {
window.fb_param = {}; // must be global by adding `window.`
fb_param.pixel_id = '123456789';
fb_param.value = '0.00';
fb_param.currency = 'USD';
(function(){
var fpw = document.createElement('script'); fpw.async = true; fpw.src = '//connect.facebook.net/en_US/fp.js';
var ref = document.getElementsByTagName('script')[0];
ref.parentNode.insertBefore(fpw, ref);
})();
});
回答by Sabir Abdul Gafoor Shaikh
I was having similar kind of issue and I would like to run multiple adds to track pixels codes and some reason I was not able to track. What I did is that, in the current page I have added pixel code in footer and javascript function to call when my ajax button get submitted.
我遇到了类似的问题,我想运行多个添加来跟踪像素代码以及我无法跟踪的某些原因。我所做的是,在当前页面中,我在页脚和 javascript 函数中添加了像素代码,以便在我的 ajax 按钮提交时调用。
First refer to Facebook documentation page
首先参考 Facebook 文档页面
How to track Multiple Conversion Events
如何跟踪多个转化事件
After the base code snippet is installed, you can track multiple conversions within the same web page by making multiple _fbq.push('track') calls for each conversion pixel ids. For example:
安装基本代码段后,您可以通过为每个转化像素 ID 进行多次 _fbq.push('track') 调用来跟踪同一网页中的多次转化。例如:
_fbq.push(['track','<pixel_id1>',{'value':'10.00','currency':'USD'}]);
_fbq.push(['track','<pixel_id2>']);
How to track In-Page Events
如何跟踪页内事件
After the base code snippet is installed, you can track in-page actions, such as clicks on a button, by making a _fbq.push('track') call for the conversion pixel through registering different event handlers on an HTML DOM element. For example:
安装基本代码片段后,您可以通过在 HTML DOM 元素上注册不同的事件处理程序来对转换像素发出 _fbq.push('track') 调用,从而跟踪页面内操作,例如单击按钮。例如:
function trackConversionEvent(val, cny) {
var cd = {};
cd.value = val;
cd.currency = cny;
_fbq.push(['track', '<pixel_id>', cd]);
}
<button onClick="trackConversionEvent('10.00','USD');" />
Also, add the facebook pixel tracking code chrome addon and refer the facebook pixel helper page: https://developers.facebook.com/docs/ads-for-websites/pixel-troubleshooting
此外,添加 facebook 像素跟踪代码 chrome 插件并参考 facebook 像素帮助页面:https: //developers.facebook.com/docs/ads-for-websites/pixel-troubleshooting
See my below solution/answer
请参阅我的以下解决方案/答案
Facebook tracking code in the current page (function() { var _fbq = window._fbq || (window._fbq = []); if (!_fbq.loaded) { var fbds = document.createElement('script'); fbds.async = true; fbds.src = '//connect.facebook.net/en_US/fbds.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(fbds, s); _fbq.loaded = true; } })(); window._fbq = window._fbq || []; window._fbq.push(['track', 'yourid', {'value':'1.00','currency':'USD'}]);
当前页面中的 Facebook 跟踪代码 (function() { var _fbq = window._fbq || (window._fbq = []); if (!_fbq.loaded) { var fbds = document.createElement('script'); fbds .async = true; fbds.src = '//connect.facebook.net/en_US/fbds.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(fbds, s) ; _fbq.loaded = true; } })(); window._fbq = window._fbq || []; window._fbq.push(['track', 'yourid', {'value':'1.00','currency':'USD'}]);
<!-- Facebook Conversion -->
<script>(function() {
var _fbq = window._fbq || (window._fbq = []);
if (!_fbq.loaded) {
var fbds = document.createElement('script');
fbds.async = true;
fbds.src = '//connect.facebook.net/en_US/fbds.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(fbds, s);
_fbq.loaded = true;
}
})();
window._fbq = window._fbq || [];
window._fbq.push(['track', 'yourid', {'value':'1.00','currency':'USD'}]);
</script>
And the javascript code to call when ajax form submit or button click
以及在ajax表单提交或按钮点击时调用的javascript代码
<script>
function trackConversionEvent(val, cny) {
var cd = {};
cd.value = val;
cd.currency = cny;
_fbq.push(['track', 'yourid1', cd]);
_fbq.push(['track', 'yourid1', cd]);
}
</script>
and the call the function when ajax called
以及调用ajax时调用的函数
jQuery(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"process.php",
success: function() {
**trackConversionEvent**('1.00','USD');
}
......
回答by Tessa
Facebook has updated their pixels, so I created my own custom function to call that will dynamically put the parameters together to submit to Facebook.
Facebook 更新了他们的像素,所以我创建了自己的自定义函数来调用,它将动态地将参数放在一起提交给 Facebook。
Step 1. On every page, make sure you've initialised your pixelin the headelement of the page.
步骤 1. 在每个页面上,确保您已在页面的head元素中初始化您的像素。
Step 2. Add this custom function I created (it's a bit verbose as it is the first draft, so I'm sure there are ways to optimise it for your benefit).
步骤 2. 添加我创建的这个自定义函数(由于它是初稿,它有点冗长,所以我相信有一些方法可以优化它以让您受益)。
triggerFacebookPixel: function(type, price, product_id, product_name, product_category, num_items) {
//See https://developers.facebook.com/docs/ads-for-websites/pixel-events/v2.8#events for documentation
//type = "ViewContent"|"AddToCart"|"Search"|"AddToWishlist"|"InitiateCheckout"|"AddPaymentInfo"|"Purchase"|"Lead"|"CompleteRegistration"
//product_id = Numeric Product ID. String or Integer accepted for single product events, or an array of integers for multiple products.
//price = Decimal/Float number of individual product's price or total price paid in conversion, or the user's status for 'CompleteRegistration'
//product_name = Optional. String of individual product's name or string of search query
//product_category = Optional. String of product category, hierarchy's accepted. E.g. "Clothing > Shirts > Men's > T-Shirts"
//num_items = Optional. Total number of products.
var data = {
value: typeof(price) == 'string' ? parseFloat(price) : price,
currency: 'USD'
}
switch (type) {
case 'Search':
data.content_ids = product_id;
data.search_string = product_name;
if (product_category !== undefined && product_category != '') {
data.content_category = product_category;
}
break;
case 'Lead':
data.content_name = product_name;
data.content_category = product_category;
break;
case 'CompleteRegistration':
data.status = product_id;
data.content_name = product_name;
break;
default:
//Product Specific Calls
//ViewContent|AddToCart|AddToWishlist|InitiateCheckout|AddPaymentInfo|Purchase
if (num_items == 1) {
data.content_ids = [typeof(product_id) == 'string' ? parseInt(product_id) : product_id];
data.content_category = product_category;
data.content_name = product_name;
} else {
data.content_ids = product_id;
}
//"num_items" is only a parameter used in these two types
if (type == 'InitiateCheckout' || type == 'Purchase') {
data.num_items = num_items
}
//"content_type" is only a parameter used in these three types
if (type == 'Purchase' || type == 'AddToCart' || type == 'ViewContent') {
data.content_type = 'product';
}
break;
}
fbq('track', type, data);
}
Step 3. Call that function with the appropriate parameters.
步骤 3. 使用适当的参数调用该函数。
For your thank you pop-up after a purchase, the pixel is fired differently if the user purchases 1 item as opposed to multiple items. Basically, Facebook accepts parameters for product names and categories if it's just one product, but doesn't accept those parameters if it's multiple products.
对于购买后的感谢弹出窗口,如果用户购买 1 件商品而不是多件商品,则像素会以不同的方式触发。基本上,如果它只是一种产品,Facebook 接受产品名称和类别的参数,但如果它是多种产品,则不接受这些参数。
For the following examples, here is some sample product data of a user purchasing 1 item:
对于以下示例,以下是用户购买 1 件商品的一些示例产品数据:
- Product Name: "My Super Awesome T-Shirt"
- Product ID: 182
- Product Category: "Clothing > Shirts > T-Shirts"
- Total amount user paid (including shipping/handling & tax): $10.84
- 商品名称:《我的超棒T恤》
- 产品编号:182
- 产品类别:“服装 > 衬衫 > T 恤”
- 用户支付的总金额(包括运费/手续费和税费):10.84 美元
And here's the function you'd call on the confirmation:
这是您在确认时调用的函数:
triggerFacebookPixel('Purchase', 10.84, 182, 'My Super Awesome T-Shirt', 'Clothing > Shirts > T-Shirts', 1);
When a user purchases multiple items, the pixel handles it differently, excluding the product names and categories and only sending their ID's. So let's pretend our user purchased these two items:
当用户购买多件商品时,像素会以不同的方式处理它,不包括产品名称和类别,只发送他们的 ID。所以让我们假设我们的用户购买了这两个项目:
- Product ID's: 182 and 164 (the shirt and something else)
- Total amount user paid (including shipping/handling & tax): $24.75
- 产品 ID:182 和 164(衬衫和其他东西)
- 用户支付的总金额(包括运费/手续费和税费):24.75 美元
This is how you'd use the function:
这是您使用该功能的方式:
triggerFacebookPixel('Purchase', 24.75, [182, 164], '', '', 2);
For other standard events as defined by Facebookregarding products, you can use this same function for "ViewContent", "AddToCart", "AddToWishlist", "InitiateCheckout", and "AddPaymentInfo". Just change "Purchase" to any of those key words in your call.
对于Facebook 定义的其他关于产品的标准事件,您可以对“ViewContent”、“AddToCart”、“AddToWishlist”、“InitiateCheckout”和“AddPaymentInfo”使用相同的函数。只需将“购买”更改为通话中的任何关键词即可。
The other events aren't necessarily related to products: "Lead", "Search", and "Complete Registration". You can still use this function for those key words like this.
其他事件不一定与产品相关:“Lead”、“Search”和“Complete Registration”。对于像这样的关键字,您仍然可以使用此功能。
Example: user searchedfor "blue shirts":
示例:用户搜索“蓝色衬衫”:
triggerFacebookPixel('Search', 0, [], 'blue shirts');
If you want to pass a product category in the user search function, you can pass that as a string at the end. I can't think of a use-case scenario where you'd know what category the user is searching for. Unless you used this in the event that the product appears in the search results and the user clicked on it from the search page. That might be what this function is actually for but the documentation isn't quite clear on that. If that's the case for you, then simply change the 0 and empty array to the actual values (price and product ID, respectively) of the product that was clicked on from the search results page, and add its category as a string as the last parameter after the search string.
如果你想在用户搜索功能中传递一个产品类别,你可以在最后将它作为一个字符串传递。我想不出一个用例场景,你会知道用户正在搜索什么类别。除非您在产品出现在搜索结果中并且用户从搜索页面单击它的情况下使用此选项。这可能是这个函数的实际用途,但文档对此并不十分清楚。如果是这种情况,那么只需将 0 和空数组更改为从搜索结果页面单击的产品的实际值(分别为价格和产品 ID),并将其类别作为字符串添加为最后一个搜索字符串后的参数。
Example: user submitted a form that signed them up to your newsletter:
示例:用户提交了一个表单,让他们注册了您的时事通讯:
triggerFacebookPixel('CompleteRegistration', 0, 'Signed Up', 'Newsletter');
Facebook's documentation states that "CompleteRegistration" should be used when a registration form is completed, e.g. complete subscription/signup for a service. The "Signed Up" string is the "status" parameter and the "Newsletter" string is the "content_name" parameter.
Facebook 的文档指出,在填写注册表时应使用“CompleteRegistration”,例如完成订阅/注册服务。“Signed Up”字符串是“status”参数,“Newsletter”字符串是“content_name”参数。
Example: user submitted a form that signed them up for a free 30-day trial of some service you offer (so they are now a lead), where the name of the service is "Free 30-Day Trial Service" and it's in the sub-category "Free Trials" under the category "My Services":
示例:用户提交了一个表格,为他们注册了您提供的某些服务的 30 天免费试用(因此他们现在是潜在客户),其中服务的名称是“免费 30 天试用服务”,它在“我的服务”类别下的子类别“免费试用”:
triggerFacebookPixel('Lead', 0, 'Free 30-Day Trial Service', 'My Services > Free Trials');
Facebook's documentation states that "Lead" is when a sign up is completed, e.g. click on pricing, signup for trial. I assumed that the name of the service is the parameter "content_name" and the category of the service is the "content_category" parameter.
Facebook 的文档指出,“Lead”是指注册完成后,例如点击定价、注册试用。我假设服务的名称是参数“content_name”,服务的类别是“content_category”参数。