Setting Event Parameter 'non_interaction': true not working - google-analytics

We have an event that is set for an API that we are setting up. Initially, the event was pinging the API server continuously which brought our bounce rate way down. We added 'non_interaction': true to cancel out the bounce rate issue, but it doesn't seem to be working. In addition to adding 'non_interaction': true, are there any other settings in GA that need to be updated to make this work? Maybe we are missing something?
Thank you ahead of time for your help!
Here is the code for review:
<script>
(function () {
var GA_TRACKING_ID = 'xxxxxx';
function processMessage(event) {
console.log('processMessage: Received event:');
console.log('event.data:', event.data);
console.log('event.origin:', event.origin);
if (event.data.includes('"name"')) {
console.log('Received alert for mobile page', event);
}
else {
if (event.data.startsWith('R_')) {
// GTAG.js methods
// Maps 'dimension1' to 'response_id'.
gtag('config', GA_TRACKING_ID, {
'custom_map': {'dimension1': 'response_id'}
});
// Sends a response_id event.
gtag('event', 'ev_response_id', {
'response_id': event.data,
'non_interaction': true
});
console.log('Pushed response_id : ' + event.data + ' to Google Analytics.');
}
}
console.log('processMessage: end');
}
function setSessionId() {
var sessionIdName = 'ua_session_id';
var noFirstVisit = sessionStorage.getItem('noFirstVisit')
// this is the first time
if (!noFirstVisit) {
var sessionId = Math.random().toString(36).substring(2, 10);
gtag('config', GA_TRACKING_ID, {
'custom_map': {'dimension2': sessionIdName}
});
gtag('event', 'ev_session_id', {
'ua_session_id': sessionId,
'non_interaction': true
});
console.log('Pushed ' + sessionIdName + ': ' + sessionId + ' to Google Analytics.');
sessionStorage.setItem('noFirstVisit', true);
} else {
console.log('The user already saw this page.')
// close and reopen the tab to clear the session storage
}
}
window.addEventListener('message', processMessage);
setSessionId();
})();
</script>

Related

SignalR Chat asp.net between user and editor

How can I make it work for the current user and any editor user account? Even if I am logged on a normal user and on incognito on one of the editor accounts, it shows like I am speaking with myself because it enters on the
name != Admin.
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
if (name == "Admin") {
// Add the message to the page.
$('#discussion').append('<p style="color:green; text-align:left; width:500px"><strong><img = src="https://www.phplivesupport.com/pics/icons/avatars/public/avatar_7.png" title="Admin">'
+ ' </strong> ' + htmlEncode(message) + '</p>');
}
else if (name != "Admin") {
// Add the message to the page.
$('#discussion').append('<p style="color:blue;text-align:right;"><strong><img = src="https://www.phplivesupport.com/pics/icons/avatars/public/avatar_71.png" title="Peter">'
+ ' </strong> ' + htmlEncode(message) + '</p>');
}
};
// Get the user name and store it to prepend to messages.
var currentMember= '#Html.Raw(#ViewBag.Name)';
alert(currentMember);
$('#displayname').val(currentMember);
//$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
That's how it worked.
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
if (name == "true") {
// Add the message to the page.
$('#discussion').append('<p style="text-align:left; text-shadow: 2px 2px 3px red"><strong><img = src="/Images/admin_icon.png" title="Admin">'
+ ' </strong> ' + htmlEncode(message) + '</p>');
}
else if (name != "true") {
// Add the message to the page.
$('#discussion').append('<p style="text-align:right;text-shadow: 2px 2px 3px teal;"><strong>'
+ ' </strong> ' + htmlEncode(message) + '<img = src="/Images/client_icon.png" title="Client">' + '</p>');
}
};
// Get the user name and store it to prepend to messages.
var currentMember= '#(User.IsInRole("Administrator") ? "true" : "false")';
//alert(currentMember);
$('#displayname').val(currentMember);
//$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>

Update dynamic data in service-worker.js

I have the below data coming in form of array from a url.
[{"title":"hey hi","body":"hello","url":"https://simple-push-demo.appspot.com/","tag":"new"}]
service-worker.js
it has the above url in fetch()
'use strict';
console.log('Started', self);
self.addEventListener('install', function(event) {
self.skipWaiting();
console.log('Installed new', event);
});
self.addEventListener('activate', function(event) {
console.log('Activatednew', event);
});
self.addEventListener('push', function(event) {
try{
console.log('Push message', event);
var ev = event;
//sample
return fetch("http://localhost/push-notifications-master/app/json.php").then(function(ev,response) {
response = JSON.parse(JSON.stringify(response));
return response;
}).then(function(ev,j) {
// Yay, `j` is a JavaScript object
console.log("j", j);
for(var i in j) {
var _title = j[i].title;
var _body = j[i].body;
var _tag = j[i].tag;
console.log("_body", _body);
}
ev.waitUntil(
self.registration.showNotification("push title", {
body: _body,
icon: 'images/icon.png',
tag: _tag
}));
});
return Promise.all(response);
}
catch(e){console.log("e", e)}
});
I am trying to see the above array data coming from that particular url in console.log("j",j);. but it shows undefined. How can i get dymanic data in sw.js Please Guide.
In your addEventListener('push' .... method, I think it might be better to wait for a response before parsing it.
Also, to be checked, but your php request should be in https (not checked by myself, but my request are on https).
Here how I do this :
event.waitUntil(
fetch('YOUR PHP URL').then(function(response) {
if (response.status !== 200) {
console.log('Problem. Status Code: ' + response.status);
throw new Error();
}
// Examine the text in the response
return response.json().then(function(data) {
if (data.error || !data.notification) {
console.error('The API returned an error.', data.error);
throw new Error();
}
var title = data.notification[0].title;
var body = data.notification[0].body;
var icon = data.notification[0].icon;
var notificationTag = data.notification[0].tag;
return self.registration.showNotification(title, {body: body,icon:icon, tag: notificationTag});
});
})
);
The json :
{"notification" : [{"title":"TITLE","body":"BODY","icon":"URL TO ICON","tag":"TAG"}]}
Hope it can be useful.

Meteor observe changes added callback

#DavidWeldon I tried your code (Meteor observe changes added callback on server fires on all item) and it's very good thank you !
However I would like to have your advise : I use it for desktop notifications : when i get one notification, there is one console log (ok), but when i get another notification (total : 2), there are two console log (I want only one console log because there is only a +1 notification)
Here is my code :
if (Notification.permission !== "granted")
Notification.requestPermission();
var query = Notifications.find({userId: Meteor.userId(), read: false});
(function() {
var initializing = true;
query.observeChanges({
added: function(id, notification) {
if (!initializing) {
console.log(notification);
}
}
});
initializing = false;
})();
Thank you for your help ! :)
You could use another flag in there?
if (Notification.permission !== "granted")
Notification.requestPermission();
var query = Notifications.find({userId: Meteor.userId(), read: false});
(function() {
var initializing = true;
var firstNotif = true;
query.observeChanges({
added: function(id, notification) {
if (!initializing && firstNotif) {
firstNotif = false;
console.log(notification);
}
}
});
initializing = false;
})();
Finally I found an answer, exploring this post in discover meteor : https://www.discovermeteor.com/blog/template-level-subscriptions/
(in my question, I was working in Template.notifications.helpers)
Here's my new code :
Template.notifications.onCreated(function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
var instance = this;
instance.autorun(function () {
var query = Notifications.find({userId: Meteor.userId(), read: false});
query.observeChanges({
added: function(id, notification) {
var notification = new Notification('Notification', {
icon: '',
body: "You got a new notification !"
});
}
});
});
});

Google Analytics isn't working with Meteor

I'm trying to use this technique http://www.bicobic.com/posts/BkFDo4CqcSnGcGtri to add the google analytics to Meteor, but it's not working (I already checked with the Google Analytics Debugger). And I'm trying with the Universal Analytics code.
Here is my code
<template name="ganalytics">
<div id="ganalytics">
</div>
</template>
Meteor.startup(function() {
isGanalyticsLoaded = false;
//a scriptloaderfunction
//if the script jsE1 loaded the callback is executed
myScriptLoader = function funcMyScriptLoader(jsEl, callback) {
if (window.attachEvent) {
// for IE (sometimes it doesn't send loaded event but only complete)
jsEl.onreadystatechange = function funcOnReadyStateChange() {
if (jsEl.readyState === 'complete') {
jsEl.onreadystatechange = "";
} else if (jsEl.readyState === 'loaded') {
jsEl.onreadystatechange = "";
}
if (typeof callback === 'function') {
callback();
}
};
} else {
// most browsers
jsEl.onload = function funcOnLoad () {
if (typeof callback === 'function') {
callback();
}
};
}
};
});
Template.ganalytics.rendered = function() {
if(!isGanalyticsLoaded) {
window['GoogleAnalyticsObject']='ga';
window['ga']=window['ga']||function(){
(window['ga'].q=window['ga'].q||[]).push(arguments)
}, window['ga'].l=1*new Date();
var myGAJs = document.createElement('script'),
s = document.getElementsByTagName('script')[0];
myGAJs.type ='text/javascript';
myGAJs.async = true;
myGAJs.src = '//www.google-analytics.com/analytics.js';
myScriptLoader(myGAJs, function funcEventLoaded() {
isGanalyticsLoaded = true;
ga('create', 'UA-XXXXXX', 'url');
ga('send', 'pageview');
});
s.parentNode.insertBefore(myGAJs, s);
}
};
<template name="layout">
<div>
{{yield}}
</div>
{{yield 'ganalytics'}}
</template>
What could be wrong with my code?
Thanks in advance.
The newer Google Analytics snippet doesn't seem to work in Meteor but putting this older, optimized style in the HEAD does:
var _gaq=[['_setAccount','UA-xxx'],['_setDomainName', 'example.com'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
You can also do this to log client-side errors to GA:
// log client-side errors to Google Analytics
window.onerror = function(message, file, line) {
_gaq.push(['_trackEvent', 'JS Error', file + ':' + line + '\n\n' + message]);
};

auto generate download events for google tag manager

I've been experimenting with auto generating events for google tag manager.
We have a script that we have used with traditional async analytics that generates onclick events for downloads, emails and external clicks.
I modified it to generate a GTM event instead of a standard analytics event as follows:
if (typeof jQuery != 'undefined') {
jQuery(document).ready(function($) {
var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;
var baseHref = '';
if (jQuery('base').attr('href') != undefined)
baseHref = jQuery('base').attr('href');
jQuery('a').each(function() {
var href = jQuery(this).attr('href');
if (href && (href.match(/^https?\:/i)) && (!href.match(document.domain))) {
jQuery(this).click(function() {
var extLink = href.replace(/^https?\:\/\//i, '');
dataLayer.push ({'eventCategory' : 'External', 'eventAction' : 'click', 'eventLabel': extLink, 'event' : 'autoevent'});
if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
setTimeout(function() { location.href = href; }, 200);
return false;
}
});
}
else if (href && href.match(/^mailto\:/i)) {
jQuery(this).click(function() {
var mailLink = href.replace(/^mailto\:/i, '');
dataLayer.push({'eventCategory' : 'Email', 'eventAction' : 'click', 'eventLabel': mailLink, 'event' : 'autoevent'});
});
}
else if (href && href.match(filetypes)) {
jQuery(this).click(function() {
var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
var filePath = href;
dataLayer.push({'eventCategory' : 'Download', 'eventAction' : 'click', 'eventLabel': filePath', 'event' : 'autoevent'});
if (jQuery(this).attr('target') != undefined && jQuery(this).attr('target').toLowerCase() != '_blank') {
setTimeout(function() { location.href = baseHref + href; }, 200);
return false;
}
});
}
});
});
}
Inside GTM I would listen for an event called autoevent, which would generate an event tag with values for Category, Action and Label.
I have been experimenting with a wordpress site so far.
My first attempt had the above script declared in the head.
The GTM code was in the body, as required.
Using the GA debugger in chrome, I am getting a JS error Uncaught SyntaxError: Unexpected identifier
on the line that issues the dataLayer push.
My Javascript sux, so I took a guess and declared the dataLayer above the GTM code, and moved the auto generating script below the GTM code, so that the dataLayer would be fully declared.
Same error occurs.
Any suggestions?
You have an extra single quote on filePath:
dataLayer.push({'eventCategory' : 'Download', 'eventAction' : 'click', 'eventLabel': filePath', 'event' : 'autoevent'});

Resources