javascript - Facebook Ads:如何创建像素自定义Javascript事件以检测YouTube视频的点击

标签 javascript wordpress youtube facebook-ads-api youtube-iframe-api

假设我们有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=1205376682832142https://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/

相关文章:

wordpress - 如何在背景图片上正确地重新定位报名表和按钮?

javascript - 如何在 iPad 中通过 javascript 停止 Youtube 视频(不是 HTML5)

javascript - jQuery 当使用 iframe 时,我应该尝试合并 jQuery 的内部和外部实例吗?

javascript - 在 node.js 中扩展类的不同方式

javascript - 使用 jquery 获取 <a> 选择器的 Id

javascript - JQuery 循环隐藏项目

php - 如何在 Wordpress 插件中加载 Javascript

wordpress - 如何创建自定义 api 端点?

javascript - 覆盖YouTube的恢复播放功能?

javascript - 显示无属性会停止 Firefox 中的 youtube iframe 播放