I’ve been doing some facebook pixel and google analytics goals set up for a client who does video embeds in website. Searched around and found wisitia having the ability to segment your traffic by placing the pixel only if visitor watch the video to some extend https://wistia.com/blog/retargeting-with-video
For youtube I developed a piece of script which does the same thing.
How it works
For developers YouTube has developed an API to extend functionality of embedded videos, called “iframe api”. As the name suggest this only works if you’re embedding the video somewhere. Once you place the script in your page, it will load the youtube video and keep an eye on it’s progress. Once it passes the defined progress (in percentage) it will go ahead and place the facebook pixel code in the page. It’s using the image version of the pixel. One drawback this script has is, it can’t detect if user seek to a specific time of the video or not.
You’ll need to be comfortable with html and css to move along, but if you get stuck somewhere comment in this post and I’ll try to help.
Step #1: Place the code in the page
Instead of pasting youtube embed code, paste below code in your page.
The final options block is the important piece, explained below;
What each option means
- autoplay: to stop autoplay of the video, make this false
- facebookPixelId: put your facebook pixel id here within quotes ie: ‘22323’
- customEvent: do you want to track this as a custom event, put it here
- height: height of the video within quotes
- width: width of the video within quotes
- videoId: id of the video within quotes
- injectionProgress: the progress of the video that needs to trigger fb pixel, if you set this to 50 visitor will get the pixel when the view 50% of the video
How to get Youtube video id
This one is pretty easy. Say the URL of the video you want to embed is
The red part is your video id, keep this part ready. Let’s get to fun parts now.
Option #1: Add fb pixel when user reach specific percentage of the video
Say you want to retarget visitors who watched the embedded youtube video 20%. This is how you do it. Assuming your facebook pixel id is 1234. Note I have changed value of injectionProgress to 20. You can copy this code and change the value to whatever you prefer.
Option #2: Add fb pixel with custom conversion when user reach specific percentage of the video
By default facebook pixel is capturing a PageView. But if you want to go further and segment your visitors who watch the video using custom conversion you can specify a value for customEvent. Not I have mentioned the even within quote.
That’s it!. If you run into any troubles please hit me up on comments below.
Optionally if you prefer to have the code in your site you can download from here
The code is open source and you can find it here – https://github.com/sahanh/youtube-segment