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]);
};
Related
I have a slideshow with youtube video's. But the problem now is that I can't trigger the onPlayerStateChange.
This is my code:
echo '<iframe id="youtube" src="http://www.youtube.com/embed/kOkQ4T5WO9E?enablejsapi=1&autoplay=1&rel=0</iframe>';
This is the JavaScript:
<script src="/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('youtube', {
events: { 'onStateChange': onPlayerStateChange }
});
}
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onPlayerStateChange(event) {
if (event.data === 0) {
alert('Video finished, next slide');
slide.next();
}
}
</script>
Is there a way to reload the iframe api when the video has ended?
I apologize, as last I knew, the YouTube API was entirely deprecated and almost no longer supported.
You're going to need to load new videos with the loadVideoByUrl function
player.loadVideoByUrl(mediaContentUrl:String,
startSeconds:Number,
suggestedQuality:String):Void
Also, you should change event.data === 0 to event.data == YT.PlayerState.ENDED
Can anyone help with a working example of recaptcha in meteor without using iframes?
I cannot make the recaptcha scripts run even when I try to run them from the client.js using jquery append.
After doing some investigations I found that I had to manually integrate the reCaptcha.
The client side code:
HTML:
<form id="mySecuredForm" novalidate>
<!-- labels and inputs here -->
<div class="row">
<div id="captcha-container">
<div id="rendered-captcha-container">loading...</div>
</div>
</div>
<div class="row">
<button type="submit" id="submit" class="submit-button">Submit</button>
</div>
</form>
JS
if (Meteor.isClient) {
Template.myTemplate.rendered = function() {
$.getScript('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js', function() {
Recaptcha.create('add_your_public_key_here', 'rendered-captcha-container', {
theme: 'red',
callback: Recaptcha.focus_response_field
});
});
}
Template['myTemplate'].events({
'submit form#mySecuredForm': function(event) {
event.preventDefault();
event.stopPropagation();
var formData = {
captcha_challenge_id: Recaptcha.get_challenge(),
captcha_solution: Recaptcha.get_response()
//add the data from form inputs here
};
Meteor.call('submitMySecuredForm', formData, function(error, result) {
if (result.success) {
//set session vars, redirect, etc
} else {
Recaptcha.reload();
// alert error message according to received code
switch (result.error) {
case 'captcha_verification_failed':
alert('captcha solution is wrong!');
break;
case 'other_error_on_form_submit':
alert('other error');
break;
default:
alert('error');
}
}
});
}
Server side code
function verifyCaptcha(clientIP, data) {
var captcha_data = {
privatekey: 'add_private_key_here',
remoteip: clientIP
challenge: data.captcha_challenge_id,
response: data.captcha_solution
};
var serialized_captcha_data =
'privatekey=' + captcha_data.privatekey +
'&remoteip=' + captcha_data.remoteip +
'&challenge=' + captcha_data.challenge +
'&response=' + captcha_data.response;
var captchaVerificationResult = null;
var success, parts; // used to process response string
try {
captchaVerificationResult = HTTP.call("POST", "http://www.google.com/recaptcha/api/verify", {
content: serialized_captcha_data.toString('utf8'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': serialized_captcha_data.length
}
});
} catch(e) {
return {
'success': false,
'error': 'google_service_not_accessible'
};
}
parts = captchaVerificationResult.content.split('\n');
success = parts[0];
if (success !== 'true') {
return {
'success': false,
'error': 'captcha_verification_failed'
};
}
return {
'success': true
};
}
Meteor.methods({
"submitMySecuredForm": function(data) {
//!add code here to separate captcha data from form data.
var verifyCaptchaResponse = verifyCaptcha(this.connection.clientAddress, data);
if (!verifyCaptchaResponse.success) {
console.log('Captcha check failed! Responding with: ', verifyCaptchaResponse);
return verifyCaptchaResponse;
}
console.log('Captcha verification passed!');
//!add code here to process form data
return {success: true};
});
There is also the possibility to listen to the post event on the server side. The http calls can be done synchronous as above or asynchronous with fibers/futures.
Server side http call to google API was inspired from:
https://github.com/mirhampt/node-recaptcha/blob/master/lib/recaptcha.js
I created a chapter selector for some youtube videos I was embedding. This method used to work but has stopped recently. I can't figure out what's going on.
I'm using their recommended format but use loadVideoById to show each chapter
<div class="wrapper">
<div id="player"></div>
<script type="text/javascript">
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: '625',
videoId: 'FE5jN0rqMtM',
events: {
'onStateChange': onPlayerStateChange
},
playerVars:{
rel: 0,
wmode: "opaque"
}
});
}
function onPlayerStateChange(evt) {
if (evt.data == 0) {
$('#video_popup').removeClass('hide_pop');
$('#video_popup').addClass('display_pop');
}
else if (evt.data == -1) {
$('#video_popup').removeClass('display_pop');
$('#video_popup').addClass('hide_pop');
}
else {
$('#video_popup').removeClass('display_pop');
$('#video_popup').addClass('hide_pop');
}
}
function chapter1() {
player.loadVideoById({'videoId': 'FE5jN0rqMtM', 'startSeconds': 0});
}
function chapter2() {
player.loadVideoById({'videoId': 'FE5jN0rqMtM', 'startSeconds': 63});
}
function chapter3() {
player.loadVideoById({'videoId': 'FE5jN0rqMtM', 'startSeconds': 135});
}
</script>
<div id="video_popup" class="hide_pop">
<div class="video_layover">
<div class="promo">Thank you for watching!<br /><br /></div>
<div class="link">Replay Video</div>
</div>
</div>
<div style="margin: 0 auto 20px auto; width:625px; height:98px; text-align:center;">
<ul class="player">
<li>Chapter 1</li>
<li>Chapter 2</li>
<li>Chapter 3</li>
</ul>
</div>
I'm guessing it is a bug though I wasn't able to find it documented. You could report the bug if you want.
Regardless, I think cueVideoById is a better method which is working for me in all browsers:
Example: JS Bin
function chapter2() {
player.cueVideoById('FE5jN0rqMtM', 63); // BETTER WAY
player.playVideo();
}
If you experienced an error like "TypeError: ytPlayer.loadVideoById is not a function",
then I believe you have to wait for the onReady event to fire.
Here is the sample code (part of) I use:
var ytPlayer;
var ytPlayerIsReady = false;
// this methods only works if defined in the global scope !!
window.onYouTubeIframeAPIReady = function () {
ytPlayer = new YT.Player('ytplayer', {
playerVars: {
enablejsapi: 1,
controls: 0,
fs: 1,
autoplay: 1,
rel: 0,
showinfo: 0,
modestbranding: 1
},
events: {
onReady: onReady,
onError: onError,
onStateChange: onStateChange
}
});
};
// youtube code for calling the iframe api
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function onError(event) {
console.log("error with code" + event.data);
}
function onStateChange(event) {
console.log("change state to " + event.data);
}
function onReady(event) {
ytPlayerIsReady = true;
console.log("I'm ready");
}
window.myVideoPlayer = {
init: function (options) {
// some arbitrary code...
// the trick is to fire options.callback,
// which contains all the logic needed
function timeout() {
setTimeout(function () {
if (false === ytPlayerIsReady) {
timeout();
}
else {
if (options.callback) {
options.callback();
}
}
}, 1000);
}
timeout();
}
};
myVideoPlayer.init({
callback: function(){
// now the youtube api is ready, you should be able to call
// loadVideoById without problems (at least it worked for me)
// ytPlayer.removeEventListener('onStateChange');
// ytPlayer.addEventListener('onStateChange', '_myYtPlayerOnChange');
// ytPlayer.loadVideoById({
// videoId: 'xxxx',
// startSeconds: 12
// });
}
});
You need to make sure var player is ready before calling loadVideoById
If(player != null)
{
loadVideoById ..
}
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'});
Now that I have found a way to initialize Google Maps with the help of Andy Joslin in this SO initialize-google-map-in-angularjs, I am looking for a way to asynchronous load a Google Map Object.
I found an example of how to do this in the phonecat project.
Notice how the JS files are loaded in this example: index-async.html
In my Jade Scripts partial that is loaded into my program I tried:
script(src='js/lib/angular/angular.js')
script(src='js/lib/script/script.min.js')
script
$script([
'js/lib/angular/angular-resource.min.js',
'js/lib/jquery/jquery-1.7.2.min.js',
'http://maps.googleapis.com/maps/api/js?key=AIzaSyBTmi_pcXMZtLX5MWFRQgbVEYx-h-pDXO4&sensor=false',
'js/app.js',
'js/services.js',
'js/controllers.js',
'js/filters.js',
'js/directives.js',
'bootstrap/js/bootstrap.min.js'
], function() {
// when all is done, execute bootstrap angular application
angular.bootstrap(document, ['ofm']);
});
When I do this and go to load the map page I get:
A call to document.write() from an asycrononously-loaded
external script was ignored.
This is how Google Maps is being loaded now as a service:
'use strict';
var app = angular.module('ofm.services', []);
app.factory('GoogleMaps', function() {
var map_id = '#map';
var lat = 46.87916;
var lng = -3.32910;
var zoom = 15;
var map = initialize(map_id, lat, lng, zoom);
return map;
});
function initialize(map_id, lat, lng, zoom) {
var myOptions = {
zoom : 8,
center : new google.maps.LatLng(lat, lng),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
return new google.maps.Map($(map_id)[0], myOptions);
}
It appears that this should be returning a promise from what I recall reading. But this AngularJS is very new to me.
here's my solution I came up without using jQuery:
(Gist here)
angular.module('testApp', []).
directive('lazyLoad', ['$window', '$q', function ($window, $q) {
function load_script() {
var s = document.createElement('script'); // use global document since Angular's $document is weak
s.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize';
document.body.appendChild(s);
}
function lazyLoadApi(key) {
var deferred = $q.defer();
$window.initialize = function () {
deferred.resolve();
};
// thanks to Emil Stenström: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
if ($window.attachEvent) {
$window.attachEvent('onload', load_script);
} else {
$window.addEventListener('load', load_script, false);
}
return deferred.promise;
}
return {
restrict: 'E',
link: function (scope, element, attrs) { // function content is optional
// in this example, it shows how and when the promises are resolved
if ($window.google && $window.google.maps) {
console.log('gmaps already loaded');
} else {
lazyLoadApi().then(function () {
console.log('promise resolved');
if ($window.google && $window.google.maps) {
console.log('gmaps loaded');
} else {
console.log('gmaps not loaded');
}
}, function () {
console.log('promise rejected');
});
}
}
};
}]);
If you using jQuery in your AngularJS app, check out this function which returns a promise for when the Google Maps API has been loaded:
https://gist.github.com/gbakernet/828536
I was able to use this in a AngularJS directive to lazy-load Google Maps on demand.
Works a treat:
angular.module('mapModule') // usage: data-google-map
.directive('googleMap', ['$window', function ($window) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
// If Google maps is already present then just initialise my map
if ($window.google && $window.google.maps) {
initGoogleMaps();
} else {
loadGoogleMapsAsync();
}
function loadGoogleMapsAsync() {
// loadGoogleMaps() == jQuery function from https://gist.github.com/gbakernet/828536
$.when(loadGoogleMaps())
// When Google maps is loaded, add InfoBox - this is optional
.then(function () {
$.ajax({ url: "/resources/js/infobox.min.js", dataType: "script", async: false });
})
.done(function () {
initGoogleMaps();
});
};
function initGoogleMaps() {
// Load your Google map stuff here
// Remember to wrap scope variables inside `scope.$apply(function(){...});`
}
}
};
}]);
Take a look of this i think its more reliable
var deferred = $q.defer();
var script = document.createElement('script');
$window.initMap = function() {
//console.log("Map init ");
deferred.resolve();
}
script.src = "//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&callback=initMap";
document.body.appendChild(script);
return deferred.promise;