假设我们有Youtube嵌入式代码:
<iframe id="my-youtube-video-id" width="560" height="315" src="https://www.youtube.com/embed/tzbrKBv-khE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
以及Facebook像素事件代码:
<button id="addToCartButton">Purchase</button>
<script type="text/javascript">
$('#$my-youtube-video-id').click(function() {
fbq('track', 'ViewContent');
});
</script>
但这似乎无法检测到有人单击视频的时间。我在使用WordPress。有什么想法我做错了吗?
PS:我正在关注以下文档:https://www.facebook.com/business/help/402791146561655?id=1205376682832142和https://developers.facebook.com/docs/facebook-pixel/implementation/conversion-tracking
最佳答案
我认为这不是Facebook Events的问题,而是iFrame的问题。 iFrame中托管的网址会收到click事件,并且不会将该事件冒泡直至iFrame元素本身。幸运的是,对于youtube视频,您可以使用嵌入式播放器API来根据播放器的状态执行操作。试试这个:
<iframe id="my-youtube-video-id" width="560" height="315" src="https://www.youtube.com/embed/tzbrKBv-khE?enablejsapi=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<script>
// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('my-youtube-video-id', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
var done;
function onPlayerStateChange(event){
if (event.data == YT.PlayerState.PLAYING && !done) {
//Here is where you can add your event, we also use the done variable to make sure the event will only fire once.
fbq('track', 'ViewContent');
done = true;
}
}
</script>
编辑:看到这个jsFiddle将log to console when the
onPlayerStateChange()
function is called
关于javascript - Facebook Ads:如何创建像素自定义Javascript事件以检测YouTube视频的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59987727/