I need to import the Facebook Pixel code in NuxtJs.
Asked
Active
Viewed 1.0k times
4 Answers
7
You can create a file in the static repository : pixel.js, with the content given by facebook :
!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', 'XXYOUR CODEXX')
fbq('track', 'PageView')
(I do not use the noscript tag with Nuxt fully based on javascrip)
Then on nuxt.conf.js file, add the lines :
script:[
{src:'pixel.js', type: 'text/javascript'}
]

Matthieu
- 71
- 1
- 4
-
or install the nuxt FB pixel module and add in the 3 line snippet into your nuxt.config.js modules block – Stephen Tetreault Aug 10 '18 at 17:26
-
Do you know how to make it dynamic pixel ID? For example, www.web.com/AAA use AAA pixel, www.web.com/BBB/shop use BBB. pixel. – Giffary Jun 25 '20 at 23:25
4
You can import as plugin too.
./plugins/facebook-events.js.
/* eslint-disable */
export default ({ app, store }) => {
/*
** Only run on client-side and only in production mode
*/
// if (process.env.NODE_ENV !== "production") return
/*
** Initialize Facebook Pixel Script
*/
if (process.browser) {
!(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', 'XXXXXXXXX-XXXXX')
app.router.afterEach((to, from) => {
/*
** Fire a page view on each route change
*/
console.log("fire pageview", store.state)
fbq("track", "PageView")
})
}
}
And import it in your nuxt.config.js, in plugins session.
plugins: [
{ src: '~/plugins/facebook-events.js' }
]

Henrique Van Klaveren
- 1,502
- 14
- 24
0
Try removing the <noscript>
tag.
See here for debugging: https://stackoverflow.com/a/49202327/1483977 And here for a bug: https://github.com/vuejs/vue/issues/9724

Michael Cole
- 15,473
- 7
- 79
- 96
-2
i can be used as ssr:false like this..
plugins : [
// ssr: false to only include it on client-side
{ src : '~/plugins/vue-notifications', ssr : false },
{ src : '~/plugins/vue-slider-component', ssr : false },
{ src : '~/plugins/network', ssr : false },
{ src : '~/plugins/web3js', ssr : false },
// {src: '~/plugins/irisws', ssr: false},
// { src : '~/plugins/iomqtt', ssr : false }
],

Soma Hesk
- 101
- 2
- 10