docbrown/app/assets/javascripts/initializers/initializeBaseTracking.js.erb
Nick Taylor f6e99dec8b
Nickytonline/homepage main feed component (#6164) [deploy]
* wip

* Removed reference to cached_tag_list as the feed enpoint only returns tag_list now.

* Removed reference to cached_properties.

* Updated <CommentsCount /> and <TagList /> to support additinal className

* wip

* wip

* Undid init scrolling for Algolia articles

* Converted homePageFeed.jsx to an ERB template to access Sprockets.

* Now the homePageFeed.jsx files is an ERB so it can load Sprockets assets.

* wip

* Removed accidental commit of debugger statement in ERB.

* Now different feed time frames are loaded based on the homepage feed tab clicked.

* Prevent default Algolia paging when on the homepage.

* Added a tiny comment about feed time frame.

* Now feed loads properly for each time frame on home page.

* prop name refactor.

* Reneabled default Algolia scrolling.

* On the homepage, we no longer overwrite article HTML with Algolia data for initial articles.

* Assumption is the proper URL for main_image of featured article will be sent in the feed.

* Fixed Google Analytics for featured article.

* No longer need the new-feed ID for checking if we're on the homepage.

* Trying to make codeclimate happy.

* wip

* Removed reference to cached_tag_list as the feed enpoint only returns tag_list now.

* Removed reference to cached_properties.

* Updated <CommentsCount /> and <TagList /> to support additinal className

* wip

* wip

* Undid init scrolling for Algolia articles

* Converted homePageFeed.jsx to an ERB template to access Sprockets.

* Now the homePageFeed.jsx files is an ERB so it can load Sprockets assets.

* wip

* Removed accidental commit of debugger statement in ERB.

* Now different feed time frames are loaded based on the homepage feed tab clicked.

* Prevent default Algolia paging when on the homepage.

* Added a tiny comment about feed time frame.

* Now feed loads properly for each time frame on home page.

* prop name refactor.

* Reneabled default Algolia scrolling.

* On the homepage, we no longer overwrite article HTML with Algolia data for initial articles.

* Assumption is the proper URL for main_image of featured article will be sent in the feed.

* Fixed Google Analytics for featured article.

* No longer need the new-feed ID for checking if we're on the homepage.

* Added postcst episodes to <Feed /> state.

* Breaking up Article.jsx to make codeclimate happy.

* wip

* Created the <TodaysPodcastEpisodes /> and <PodcastEpisode /> components.

* Fixed issues with some components that were updated for the <FeaturedArticle />

* Added tests for <FeaturedArticle />

* Barreled up <FeaturedArticle />

* Added Storybook stories for <FeaturedArticle />

* Featured articles don't display org, so removed that test.

* Added proper today's podcasts components to feed.

* Converted some leftover ERB + removed pro checkmark as it doesn't exist yet.

* Now logic is same as master for feed timeframe.

* Updated <FeaturedArticle /> snapshots.

* On frontpage, bookmark button state is managed by Preact components now.

* bookmarkedFeedItems is now a prop on <Feed />.

* Fixed logic check for initializing reading list icons.

* Now <Article /> and <FeaturedArticle /> receive a bookmarkClick prop.

* Removed beginnings of scroll handler in <Feed /> as we're using what's there already for now.

* Removed logic to not show main image on other time frame feeds as it was not correct.

* Fixed issue with 0 rendering when no podcast episodes in feed.

* Converted <SaveButton /> to a stateful component.

* wip - <Feed /> render prop now passes bookmarked feed item ID set and a click event.

* Moved FEED_ICONS to an export so it's easier to use JSX/JS in <Feed />

* Moved <Feed /> into article components.

* Now reading list save buttons work properly in Preact components.

* Fixed issue with Save buttons in Algolia paging/<Feed />

* Updated snapshots.

* Took <Feed /> out of articles barrel file as jest was trying to import FEED_ICONs which is an ERB template.

* Now the Preact feed is dynamically imported.

* Now the Preact <Feed /> only loads for a logged on user.

* Fixed <FeaturedArticle /> so that the save button behaves properly now.

* Updated article stories for Storybook.

* Putting this back to the order it was because I've removed my code changes for this block.

* Fixed when renderFeed is imported for a logged on user.

* Add podcasts to feed and render home from server

* Add padding to feature laoding div

* Update tests

* Add more loading articles

* Fix conflicts

* Add readinglist javascript to initscrolling

* Ensure first article is one with image

* Organize feed items outside of feed instead of in it

Co-authored-by: Ben Halpern <bendhalpern@gmail.com>
Co-authored-by: Josh Puetz <josh@grorichpuetz.com>
2020-02-28 14:14:47 -05:00

241 lines
7.8 KiB
Text

function initializeBaseTracking() {
var wait = 0;
var addedGA = false;
var waitingOnGA = setInterval(function() {
if (!addedGA) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
}
addedGA = true;
wait++;
if (window.ga && ga.create) {
ga('create', '<%= ApplicationConfig["GA_TRACKING_ID"] %>', 'auto');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview', location.pathname + location.search);
clearInterval(waitingOnGA);
}
if (wait > 85) {
clearInterval(waitingOnGA);
fallbackActivityRecording();
}
}, 25);
eventListening();
trackCustomImpressions();
}
function fallbackActivityRecording() {
var tokenMeta = document.querySelector("meta[name='csrf-token']")
if (!tokenMeta) {
return
}
var csrfToken = tokenMeta.getAttribute('content')
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
var screenW = window.screen.availWidth;
var screenH = window.screen.availHeight;
var dataBody = {
path: location.pathname + location.search,
user_language: navigator.language,
referrer: document.referrer,
user_agent: navigator.userAgent,
viewport_size: h + 'x' + w,
screen_resolution: screenH + 'x' + screenW,
document_title: document.title,
document_encoding: document.characterSet,
document_path: location.pathname + location.search,
};
window.fetch('/fallback_activity_recorder', {
method: 'POST',
headers: {
Accept: 'application/json',
'X-CSRF-Token': csrfToken,
},
body: JSON.stringify(dataBody),
credentials: 'same-origin'
});
}
function eventListening(){
var registerNowButt = document.getElementById("cta-comment-register-now-link");
if (registerNowButt) {
registerNowButt.onclick = function(){
ga('send', 'event', 'click', 'register-now-click', null, null);
}
}
}
function trackCustomImpressions() {
setTimeout(function(){
var ArticleElement = document.getElementById('article-body');
var tokenMeta = document.querySelector("meta[name='csrf-token']")
var isBot = /bot|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex/i.test(navigator.userAgent) // is crawler
var windowBigEnough = window.innerWidth > 1250
// Sidebar HTML variant tracking
var stickyNav = document.getElementById('article-show-primary-sticky-nav');
var sidebarHTMLVariant = document.getElementById('html-variant-article-show-sidebar');
if (sidebarHTMLVariant && ArticleElement && tokenMeta && !isBot && windowBigEnough) {
var dataBody = {
html_variant_id: sidebarHTMLVariant.dataset.variantId,
article_id: ArticleElement.dataset.articleId,
};
var csrfToken = tokenMeta.getAttribute('content');
trackHTMLVariantTrial(dataBody, csrfToken)
var successLinks = stickyNav.querySelectorAll('a,button'); //track all links and button clicks within nav
for(var i = 0; i < successLinks.length; i++)
{
successLinks[i].addEventListener('click', function() { trackHtmlVariantSuccess(dataBody, csrfToken) });
}
}
// Below article HTML variant tracking
var belowArticleHTMLVariant = document.getElementById('html-variant-article-show-below-article');
if (belowArticleHTMLVariant && ArticleElement && tokenMeta && !isBot && windowBigEnough) {
var dataBody = {
html_variant_id: belowArticleHTMLVariant.dataset.variantId,
article_id: ArticleElement.dataset.articleId,
};
var csrfToken = tokenMeta.getAttribute('content');
trackHTMLVariantTrial(dataBody, csrfToken)
var successLinks = belowArticleHTMLVariant.querySelectorAll('a,button'); //track all links and button clicks within nav
for(var i = 0; i < successLinks.length; i++)
{
successLinks[i].addEventListener('click', function() { trackHtmlVariantSuccess(dataBody, csrfToken) });
}
}
// page view
if (ArticleElement && tokenMeta && !isBot) {
var randomNumber = Math.floor(Math.random() * 10); // 1 in 10; Only track 1 in 10 impressions
if (!checkUserLoggedIn() && randomNumber != 1) {
return;
}
var dataBody = {
article_id: ArticleElement.dataset.articleId,
referrer: document.referrer,
user_agent: navigator.userAgent,
};
var csrfToken = tokenMeta.getAttribute('content');
trackPageView(dataBody, csrfToken);
var timeOnSiteCounter = 0;
var timeOnSiteInterval = setInterval(function(){
timeOnSiteCounter++
var ArticleElement = document.getElementById('article-body');
if (ArticleElement && checkUserLoggedIn()) {
trackFifteenSecondsOnPage(ArticleElement.dataset.articleId, csrfToken);
} else {
clearInterval(timeOnSiteInterval);
}
if ( timeOnSiteCounter > 118 ) {
clearInterval(timeOnSiteInterval);
}
}, 15000)
}
// display add
var adBox = document.getElementById('sponsorship-arbitrary-display-widget')
if (adBox
&& tokenMeta
&& !isBot
&& windowBigEnough
&& checkUserLoggedIn()) {
var csrfToken = tokenMeta.getAttribute('content');
trackAdImpression(csrfToken, adBox)
adBox.removeEventListener('click', trackAdClick, false );
adBox.addEventListener('click', function() { trackAdClick(csrfToken, adBox) });
}
}, 1800)
}
function trackHTMLVariantTrial(dataBody, csrfToken) {
var randomNumber = Math.floor(Math.random() * 10); // 1 in 10; Only track 1 in 10 impressions
if (randomNumber === 1) {
window.fetch('/html_variant_trials', {
method: 'POST',
headers: {
'X-CSRF-Token': csrfToken,
'Content-Type': 'application/json',
},
body: JSON.stringify(dataBody),
credentials: 'same-origin',
});
}
}
function trackHtmlVariantSuccess(dataBody, csrfToken) {
window.fetch('/html_variant_successes', {
method: 'POST',
headers: {
'X-CSRF-Token': csrfToken,
'Content-Type': 'application/json',
},
body: JSON.stringify(dataBody),
credentials: 'same-origin',
})
}
function trackPageView(dataBody, csrfToken) {
window.fetch('/page_views', {
method: 'POST',
headers: {
'X-CSRF-Token': csrfToken,
'Content-Type': 'application/json',
},
body: JSON.stringify(dataBody),
credentials: 'same-origin',
})
}
function trackFifteenSecondsOnPage(articleId, csrfToken) {
window.fetch('/page_views/' + articleId, {
method: 'PATCH',
headers: {
'X-CSRF-Token': csrfToken,
'Content-Type': 'application/json',
},
credentials: 'same-origin',
})
}
function trackAdImpression(token, adBox) {
var dataBody = {
display_ad_event: {
display_ad_id: adBox.dataset.id,
context_type: "home",
category: "impression",
}
}
window.fetch('/display_ad_events', {
method: 'POST',
headers: {
'X-CSRF-Token': token,
'Content-Type': 'application/json',
},
body: JSON.stringify(dataBody),
credentials: 'same-origin',
})
}
function trackAdClick(token, adBox) {
if (!adClicked) {
var dataBody = {
display_ad_event: {
display_ad_id: adBox.dataset.id,
context_type: "home",
category: "click",
}
}
window.fetch('/display_ad_events', {
method: 'POST',
headers: {
'X-CSRF-Token': token,
'Content-Type': 'application/json',
},
body: JSON.stringify(dataBody),
credentials: 'same-origin',
})
}
adClicked = true;
}