You are here

public function SnippetBuilder::buildSnippet in Hotjar 8.2

Same name and namespace in other branches
  1. 8 src/SnippetBuilder.php \Drupal\hotjar\SnippetBuilder::buildSnippet()

Get Hotjar snippet code.

Return value

mixed|string Hotjar snippet.

Overrides SnippetBuilderInterface::buildSnippet

1 call to SnippetBuilder::buildSnippet()
SnippetBuilder::saveSnippets in src/SnippetBuilder.php
Saves JS snippet files based on current settings.

File

src/SnippetBuilder.php, line 227

Class

SnippetBuilder
Snippet builder service.

Namespace

Drupal\hotjar

Code

public function buildSnippet() {
  $id = $this->settings
    ->getSetting('account');

  // Use escaped HotjarID.
  $clean_id = $this
    ->escapeValue($id);
  $clean_version = $this
    ->escapeValue($this->settings
    ->getSetting('snippet_version'));

  // Quote from the Hotjar dashboard:
  // The Tracking Code below should be placed in the <head> tag of
  // every page you want to track on your site.
  if ($id && $clean_id) {
    $script = <<<HJ
(function(h,o,t,j,a,r){
  h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};
  h._hjSettings={hjid:{<span class="php-variable">$clean_id</span>},hjsv:{<span class="php-variable">$clean_version</span>}};
  a=o.getElementsByTagName('head')[0];
  r=o.createElement('script');r.async=1;
  r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;
  a.appendChild(r);
})(window,document,'//static.hotjar.com/c/hotjar-','.js?sv=');
HJ;
  }
  else {
    $script = <<<HJ
// Empty HotjarID.
HJ;
  }

  // Allow other modules to modify or wrap the script.
  $this->moduleHandler
    ->alter('hotjar_snippet', $script);

  // Compact script if core aggregation or advagg module are enabled.
  if ($this
    ->isJsPreprocessEnabled() || $this->moduleHandler
    ->moduleExists('advagg')) {
    $script = str_replace([
      "\n",
      '  ',
    ], '', $script);
  }
  return $script;
}