GA Events in Javascript we can do by
ga('send', 'event', 'test', 'test','value');
I need to implement this in entire project. But there are some sections where I need to do it via PHP.
So looking for PHP library that can be added as a module via composer.
I found
Google Analytics Measurement Protocol library for PHP
PHP Analytics Events
But this one is not best. That which I'm looking for.
Tracking Id & Website only specified by once. Then just need to pass event parameters as we do in Javascript.
Does anyone come across any kind of this library?
Found this one very helpful
https://gearside.com/using-server-side-google-analytics-sending-pageviews-event-tracking/
The Google analytics javascript snippet sends data to google analytics via the measurment protocol
The measurement protocol accepts http post and http gets. This can easly be done with PHP but if you are looking for something out of the box created to do it there isnt anything official written in php that i am aware of. Your going to have to code this yourself.
Using
https://github.com/thomasbachem/php-ga
Install via
composer require united-prototype/php-ga
Below is the code
use UnitedPrototype\GoogleAnalytics;
$tracker = new GoogleAnalytics\Tracker('UA-XXXXXX-1', 'example.com');
$session = new GoogleAnalytics\Session();
// Setup visitor
$visitor = new GoogleAnalytics\Visitor();
$visitor->setIpAddress($server->get('REMOTE_ADDRESS'));
$visitor->setUserAgent($server->get('HTTP_USER_AGENT'));
//Set Event
$event = new GoogleAnalytics\Event();
$event->setCategory('Category'); // Event Category (Required)
$event->setAction('Event'); // Event Action (Required)
$event->setLabel('Label'); // Event Label (Optional)
$event->setValue(1); //integer, not required
//track event
$response = $tracker->trackEvent($event,$session,$visitor);
Works fine for me.
Related
I need to retrieve the Google Analytics Tracking ID via JavaScript for use in another script. Something like:
var ga_id = (typeof ga !== 'undefined') ? ga.getAll()[0].get('trackingId') : 'Unable to retrieve GA id'
My Analytics is loaded using Tag manager, so even though I'm running my own JavaScript quite late in the page, its not detecting the presence of the ga object. ( I can access it without a problem via the developer tools console.)
How can I ensure that ga has loaded before trying to access its properties?
It's there on window loaded and you can see it in the GTM preview like so:
I have this CJS in that var (used your code):
Although this is ample in my case, yours may differ, so what you can do is the following:
Make a custom html tag that runs on pageload and deploys a closure with a timeout in it.
In the timeout callback push a dataLayer event.
Now move the tag that you want to get the value of the property id for to the dataLayer event trigger (custom event).
This is not very elegant, but it'll work. Again, for normal implementations, Window Loaded should be ample.
This is loosely written to give a basic idea of what I'm trying achieve.
< VrButton onClick={props.userClick}>< /VrButton>
userClick={() => this.triggerTracking}
triggerTracking() {
ga('send', 'event', 'myEventCategory', 'myEventAction', 'myEventLabel');
}
I expect the code to trigger Google Analytics event tracking in the GA system when the user clicks on a button, but I get an error message - "ga is not a function".
I have GA set up in my index.html file, with the proper ID, and pulling in the latest analytics.js API.
React VR is all within a web worker context so it is not possible to access anything on your window without the use of native modules.
You can embed them directly in your client js and use the GA tracking functions as you normally would there. You will then call a function on your native module within your react VR app.
You can check out the documentation here: https://facebook.github.io/react-vr/docs/native-modules.html
Try using the window scope as:
window.ga('send', 'event', 'myEventCategory', 'myEventAction', 'myEventLabel');
I'm not familiar with React at all, but perhaps React causes some abstraction between the window and the react scope, making your ga() function unavailable.
Do next stps:
open the network debug tool of your browser.
reload your page
review loaded url list and check that www.google-analytics.com/analytics.js is loaded
If you does not see such url loaded - read google analitycks manual about how to setup google analytics on your page.
If you see such url replace url www.google-analytics.com/analytics.js with www.google-analytics.com/analytics_debug.js in your page, than reload and than go to console tab of your browser debugger and check the errors.
I am making a simple iOS share extension that will operate on web pages. It is not unlike Pinterest, in that it grabs certain info from the page. But it is different from Pinterest in that the JS used to do the grabbing is sometimes custom to the web page domain.
So in the ExtensionPreprocessingJS run() function I do the following to load and execute the custom JS:
var Action = function() {};
Action.prototype = {
run: function(arguments) {
var e = document.createElement('script');
e.setAttribute('type','application/javascript');
e.setAttribute('id','my-unique-id');
e.setAttribute('src','//mydomain.com/bookmarklet?d='+document.domain);
document.body.appendChild(e);
<some code to extract results and generate JSON>
arguments.completionFunction({ <my JSON here> });
}
};
var ExtensionPreprocessingJS = new Action
My bookmarklet endpoint provides some JS that finds the relevant info from the page for "pinning".
My problem is that this happens asynchronously and not before I pass back the results at the end of the run method using
arguments.completionFunction( <my JSON here> );
I have tried waiting for the result to be set before calling completionFunction() but the extension seems to treat that as completionFunction() not being called at all. That is, it seems the design of the share extension framework doesn't accommodate asynchronous JS. It assumes the result from the JS is available after the run() function returns.
Am I misunderstanding the share extension design, or do I need to look for a different way to do this? I do notice that Instapaper created a share extension with no native UI and I'm wondering whether this is why they did so.
Is it possible to show the documents from my drive on a webpage? I want the user to be able to click the document and download it, directly from my drive. How would I go about doing this? Thank you for your suggestions.
The fastest and easiest solution is to embed the folder using an iframe (no javascript needed). Obviously this is also the least flexible solution, although you can use CSS to change the layout of the iframe contents (see below).
Google Drive won't allow embedding of the url you would normally use. It has its X-Frame-Options header set to "SAMEORIGIN", preventing use in an iframe. So you have to use the following link, which will allow embedding:https://drive.google.com/embeddedfolderview?id=DOCUMENT_ID#VIEW_TYPE
DOCUMENT_ID is the id that is mentioned in the normal share link (which looks like https://drive.google.com/folderview?id=DOCUMENT_ID), so you can just copy that from there.
VIEW_TYPE should be either 'grid' or 'list', depending on your preference.
And if you need to change the style of the iframe content, take a look at this solution.
For HTML/JavaScript solution, look at the following links:
https://developers.google.com/drive/quickstart-js
https://www.youtube.com/watch?v=09geUJg11iA
https://developers.google.com/drive/web/auth/web-client
Here's the simplest way using JavaScript, most of the complexity is in
your WebApp authorization. The example below reads files IDs, names and description in a folder you specify.
- go to: https://cloud.google.com/console/project
and create a new project "xyz"
- Select "APIs & auth", disable the ones you don't need, enable "Drive API"
- Select "Credentials",
push "CREATE NEW CLIENT ID" button
x Web Application
Authorized Javascript origins: "https://googledrive.com/"
Authorized redirect URI: "https://googledrive.com/oauth2callback"
it will result in:
Client ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com
Email address: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com
Client secret: xxxxxxxxxxxxxxxxxxxx
Redirect URIs: https://googledrive.com/oauth2callback
Javascript Origins: https://googledrive.com/
- in the code below, replace
CLIENT_ID with xxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com
FOLDER_ID with the ID you see in the folder address line,
https://drive.google.com/?tab=mo&authuser=0#folders/xxxxxxxxxxxxxxxxxxx
- run it, authorize
I don't know if you read JS, the code can be followed from bottom up, I made is as simple as possible.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var FOLDER_ID = '.xxxxxxxxxxxxxxxxxx'; // the folder files reside in
var CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com';
var SCOPE = //'https://www.googleapis.com/auth/drive';
[
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file', // for description,
];
function rsvpCB(resp) {
var picAlbumLst = '<ul>\n';
for (i=0; i<resp.items.length; i++)
picAlbumLst += (
' <li>'+resp.items[i].id+', '+resp.items[i].title+', '+resp.items[i].description+'</li>\n');
picAlbumLst += "</ul>\n";
$('#container').append(picAlbumLst);
}
function rqstCB() { //test # https://developers.google.com/drive/v2/reference/files/list
var rv = gapi.client.drive.files.list({
'q': '"'+FOLDER_ID+'" in parents and trashed = false',
'fields' : 'items(id,title,description)' //'items(id,title,description,indexableText)'
}).execute(rsvpCB);
}
// authorization server reply
function onAuthResult(authResult) {
var authButton = document.getElementById('authorizeButton');
authButton.style.display = 'none';
if (authResult && !authResult.error) { // access token successfully retrieved
gapi.client.load('drive', 'v2', rqstCB);
} else { // no access token retrieved, force the authorization flow.
authButton.style.display = 'block';
authButton.onclick = function() {
checkAuth(false);
}
}
}
// check if the current user has authorized the application.
function checkAuth(bNow) {
gapi.auth.authorize({'client_id':CLIENT_ID, 'scope':SCOPE, 'immediate':bNow}, onAuthResult);
}
// called when the client library is loaded, look below
function onLoadCB() {
checkAuth(true);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=onLoadCB"></script>
<body style="background-color: transparent;">
<input type="button" id="authorizeButton" style="display: none" value="Authorize" />
<div id="container">
</div>
</body>
This should be done with Google API. You can search google drive php api list files on google. And also I found this and this on SO.
Here are some main points:
Do you want anyone with the URL to be able to see your document? You can share a document as public to anyone on the internet. Plus you can set read access to specific folders. Just right click a Google Doc file, and choose 'Share' from the short cut menu.
I'm assuming you want people to download your docs, even when you are not signed in. This is called 'Offline Access', and is one of many terms you'll need to figure out in order to do all of this with a program.
If you only want to give read access to the user, using JavaScript, jQuery, etc on the front end is a viable option. You can also do this in PHP, it's just a matter of personal preference.
To do all of this in code, you need to grant authorization to read your files. The oAuth2 process has multiple steps, and it's good to understand the basic flow. Setting up the code and the webpages to initially grant authorization, then retrieve and store the tokens can get confusing.
Your Google Project has a setting for where the origin of the authorization request is coming from. That is your website. But if you want to develop and test locally, you can set the Javascript Origins to http://localhost
How much time do you have, and how much programming experience? Would it be easier to give the user a few lines of instruction to "Manually" download your file, rather than program the authorization check?
Putting the document into your webpage is the easy part.
In order to embed a Google doc in your website, go to your Google Drive, open a document and choose File then Publish to Web, and you will be given an HTML iFrame Tag that can be embedded into you web page. You can change the height and width of the iFrame to match the document size. iFrame Instructions W3Schools
Downloading your document can be done very easily from the online version of a shared document just by choosing FILE and then DOWNLOAD AS from the menu.
To get up and running fast, just give the user a couple lines of instructions on how to download "Manually", then see if you can program the code.
Provide a link to your shared document instead of programming the button, and then work on the code.
Search Git Hub for Google Drive, you might find something there.
Some of the official Google code examples are way more complicated than you need, and will take a long time to figure out. The code examples in the documentation pages are simpler, but are almost never complete functioning code examples. You'll need to put lots of pieces of the puzzle together to make it work.
Is there any Google Analytics testing/sandbox environment for testing your JS custom code before putting it to live system?
I don't want to use my real tracking ID to see if everything is correct on my dev. environment, neither I want to put my code untested live...
Is there any techniques or maybe some fake Analytics tracking lib I could use for testing?
The Google Analytics Debugger Chrome Extension is very helpful in testing Google Analytics code. The extension outputs the data sent to Google Analytics to the JavaScript Console Window. The days of you...waiting around...hoping/praying to see your test Pageviews in Google Analytics are over.
Below is an example of some of the output the extension prints to the JavaScript Console Window:
Track Pageview
Tracking beacon sent!
Account ID : UA-2345678-90
Page Title : About
Host Name : www.yourdomain.org
Page : /about
Referring URL : -
Language : en-us
Encoding : UTF-8
Flash Version : 11.1 r102
Java Enabled : true
Screen Resolution : 1680x1050
Color Depth : 16-bit
Ga.js Version : 5.2.4d
Cachebuster : 476867651
I believe it is possible, but you have to tell it to not use the domain when setting the cookie...
var pageTracker = _gat._getTracker("UA-12345-1");
pageTracker._setDomainName("none");
pageTracker._trackPageview();
And you probably have to use a legitimate tracker ID.
Also, be sure to see Analytics Customizations: Using a Local Server
Why don't you just create a new tracking code / profile in GA? That way you can see the results on your dev server and then switch to the real tracking number when you move to live.
I think a lot has changed since the question was asked, but I believe I should add this here just for the new visitors since it is not in the answers.
Google Analytics now has a Sandbox Account that you can create. Check out the source for the direct announcement by them.
Short instructions from the link:
If you already have a Google Analytics account, you'll need to create a new one as your "sandbox" by following these instructions:
Click Admin at the top of any Analytics page.
In the Account column, click the menu, then click Create new account.
Follow the instructions.
Source:
https://groups.google.com/forum/#!category-topic/digital-analytics-fundamentals/6EYCkNdE2No
I think it should be done with "views" in 2019.
Create views for development and production https://support.google.com/analytics/answer/1009714?hl=en
Create a custom dimension "environment" = "test" / "prod". Send it from website/app.
Create filters by custom dimension "environment" on view level https://www.bounteous.com/insights/2015/10/16/filtering-session-user-custom-dimensions-google-analytics/
Maybe for some projects filters can be done by URL instead of custom dimensions.