You are here

function facebook_pixel_page_attachments in Facebook Pixel 8

Implements hook_page_attachments().

File

./facebook_pixel.module, line 32
Contains facebook_pixel.module..

Code

function facebook_pixel_page_attachments(array &$page) {
  $config = \Drupal::config('facebook_pixel.facebookpixelconfig');
  $id = $config
    ->get('facebook_id');

  // Facebook Pixel must be configured to proceed.
  if (empty($id)) {
    return;
  }
  $jsString = Xss::filter(json_encode($id));
  $script = '!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\', ' . $jsString . ');fbq(\'track\', "PageView");';

  // Add registered events to the script execution.

  /** @var \Drupal\facebook_pixel\FacebookEvent $facebook_event */
  $facebook_event = \Drupal::service('facebook_pixel.facebook_event');
  foreach ($facebook_event
    ->getEvents() as $event) {
    $script .= 'fbq("track", "' . Xss::filter($event['event']) . '", ' . Xss::filter(json_encode($event['data'])) . ');';
  }
  $page['#attached']['html_head'][] = [
    [
      '#tag' => 'script',
      '#value' => $script,
    ],
    'facebook_tracking_pixel_script',
  ];
}