Is there a way to stop Google Analytics counting development work as hits? - development-environment

I have added the JavaScript that I need to the bottom of my pages so that I can make use of Google Analytics. Only problem is that I am sure that it is counting all my development work as hits. Seeing as I probably see some of those pages a hundred times a day it will really skew my readings. Is there a way to turn it off from a particular IP address or is this something that should be built into my build process so it only gets added when I build for deployment?

I like the simple approach of using javascript. It works anywhere.
<script type="text/javascript">
if (document.location.hostname.search("myproductiondomainname.com") !== -1) {
//google analytics code goes here
}
</script>

Yeah, you go into Analytics Settings, edit your site, and +Add Filter to define a filter that excludes your IP address.
Past data is not regenerated with filters applied, so you'll only have the benefit of them moving forward.

It's 2014 and I'm still unsatisfied with all existing solutions...
IP filters require a static IP address. What if I'm working from home or from a coffee shop?
Checking host name eliminates hits from a dev environment, but what if I'm debugging the live site?
Editing server configurations is annoying/advanced and multiple domains are complicated.
Opt-Out extensions either block hits on all websites or none at all depending on who you ask.
So, I created my own Browser Extension...
https://chrome.google.com/webstore/detail/lknhpplgahpbindnnocglcjonpahfikn
It follows me wherever I go
It works on a dev environment and on live/public domains
It only affects me and the sites that I'm developing
It turns on/off with one click
It's easy to verify that it is truly not sending any data to analytics
It works by keeping a "developer cookie" set on your machine at all times just for the domains that you choose. You then simply check for this cookie in your script before sending any data to Analytics. You customize your own unique NAME and VALUE for the cookies in the extension's settings. This can easily be used by a team of people, so developers, content creators, proofreaders, and anyone else in your organization can all view pages without inflating the statistics.
Examples of how to put the code into your pages...
JavaScript
if (window.location.host==="mydomain.com" || window.location.host==="www.mydomain.com") {
if (document.cookie.indexOf("COOKIENAME=COOKIEVALUE") === -1) {
// Insert Analytics Code Here
}
}
PHP
if ($_SERVER['HTTP_HOST']==="mydomain.com" || $_SERVER['HTTP_HOST']==="www.mydomain.com") {
if (#$_COOKIE["COOKIENAME"] !== "COOKIEVALUE") {
// Insert Analytics Code Here
}
}
Verifying that the HOST name equals the domain of your live site ("mydomain.com") ensures that the analytics data will never be sent by ANY visitor while viewing from a test domain such as "localhost" or "beta.mydomain.com". In the examples above, "www.mydomain.com" and "mydomain.com" are the two valid domains where we DO want visits to be recorded.
The live site sends data to analytics as expected UNLESS a developer cookie is found with matching values. If it sees that unique cookie set on your device, then your visit will not count towards your totals in Google Analytics or whatever other analytics tool you prefer to use.
Feel free to share my solution and use my extension to keep those cookies set.

If you're not using static IP, setting IP filters on GA can't help you.
Set an environment variable and conditionally display it. Take the following Ruby on Rails code, for instance:
<% unless RAILS_ENV == "development" %>
<!-- your GA code -->
<% end %>
You can extend this behavior every language/framework you use on any operating system. On PHP, you can use the getenv function. Check it out the Wikipedia page on Environment Variables to know how to proceed on your system.

You can use this code
<script>
var host = window.location.hostname;
if(host != "localhost")
{
// your google analytic code here
}
</script>

The solution is to use Google Tag Manager (GTM) to handle your Google Analytics. This will allow you to only fire Google Analytics on your production domain without having to write any conditionals in your site's code. Here's how to do it:
In GTM, set a Trigger that only fires when the Page Hostname contains your production domain.
Then set a Tag for Universal Analytics and make its Trigger the one you just created.

We setup a 2nd google analytics tracking code for development and QA work -- actually comes in handy when you want to test your analytics integration, also ensures one doesn't have bleedover into production stats.

If You are behind NAT or You can't for other reason give Your IP to Google Analytics, then the simplest method is to set the google analytics domain to localhost (127.0.0.1), from now when You open Your browser, all request to Google Analytics will be directed to Your working station, without knowledge of Google Analytics.

To disable localhost hits, just create a filter to exclude localhost. Go to Admin -> Property -> View Settings to do so. Check the following screenshot for some help.
To disable production URL hits for yourself if you visit using a non-static IP, you can use a Chrome extension like Developer Cookie to skip running the Google Analytics code if it's you.
I personally don't do this since I use an Ad Blocker which already blocks Google Analytics on my browser.

There are a few Chrome extensions that do this for you, like https://chrome.google.com/webstore/detail/fadgflmigmogfionelcpalhohefbnehm
Very convenient if your IP address is not static.

Add this line before your Google Analytics async code runs to disable tracking for that web property ID:
window['ga-disable-UA-XXXXXX-Y'] = true;
UA-XXXXXX-Y corresponds to the web property ID on which you would like to disable tracking.
From: https://developers.google.com/analytics/devguides/collection/gajs/

Use a custom metric to filter all this traffic.
When you init GA in your app, set a custom flag to track developres:
// In your header, after the GA code is injected
if( <your_code_to_check_if_is_dev> ) {
ga('set', 'is_developer', 1 );
}
Then add a filter in your GA Account to remove these results.
Admin > Account > All Filters > Add Filter > User Defined

For Google Analytics 4 (GA4), you can create a rule to define IP addresses whose traffic should be marked as internal.
Define Internal Traffic
Path: Admin > Property > Data Streams > select your stream > More Tagging Settings > Define internal traffic
Define a rule to match one or more IPs that represent your internal traffic.
GA4 Data Filters
Path: Admin > Property > Data Settings > Data Filters
You will find the default filter "Internal Traffic" set to "Testing" mode.
Change to "Active" to enable the filter.

I use Ad Blocker for Firefox, it can specifically block the Google analytics tracking script. Since firefox is my primary development browser it works great until i need to test my work in other browsers.

Probably not helpful to you, but I solved this problem by writing a custom ASP.NET server control that injects the required JavaScript. I then added the live URL to web.config and then only made the control visible when the host name matched the live URL in web.config.

If you have a react application and you have ejected the app(this could work for CRA as well). You can make use of the below code snippet in the index.html page.
<script type="text/javascript">
if("%NODE_ENV%"==="production"){
//your analytics code
}

Like people are mentioning you can either host the google-analytics.com domain locally or setup a function to see if you are working in your development network.
Keep in mind if http://www.google-analytics.com/ga.js does not load and your using onclick javascript functions to help track clicks on page elements.
IE:
onclick="javascript:pageTracker._trackPageview('/made/up/folder/reference');
Your going to have JavaScript errors that will stop jQuery or other robust JavaScript functions from functioning.

Just as an additional option for this, I have a development server with lots of different sites and developers. This meant that I wasn't particularly happy with the 3 main options
hosts file- problematic with lots of developers and open to human error
if/else development block on every site etc
configuration on GA website - some clients have their own GA accounts; would have to be completed on every site with the potential to be forgotten/overlooked
Rather than implementing the various options in the other answers here I approached the problem in the following way. In the global httpd.conf (rather than a site specific one) I used the apache module mod_substitute to simulate the effect the hosts file fix in another answer has, but for every development site, and every developer automatically.
Enable the module
CentOS: Open /etc/conf/httpd.conf and add the following line
LoadModule substitute_module modules/mod_substitute.so
Ubuntu/Debian: Run the following command
sudo a2enmod substitute
Once you've got the module enabled add the following lines to your httpd global config file
CentOS: /etc/conf/httpd.conf
Ubuntu/Debian: /etc/apache2/httpd.conf
# Break Google Analytics
AddOutputFilterByType SUBSTITUTE text/html
Substitute "s|.google-analytics.com|.127.0.0.1|n"
Then restart apache
CentOS: service httpd restart
Ubuntu/Debian: /etc/init.d/apache2 restart
What this does is replace all text matching .google-analytics.com with .127.0.0.1 when apache serves the page so your page renders with analytics code similar to the below example
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.127.0.0.1/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

I know this post is super old, but none of the solutions met my needs. Not only did I want to remove dev work from GA (and FB), but I also wanted to have some folks within the company not be counted in GA and FB. So I wanted a relatively easy method for those folks to exclude themselves from analytics without a plugin, or ruling out a domain ip (as folks with laptops wander).
I created a webpage that users can go to and click a link to opt out of the GA and FB tracking. It places a cookie for the site. Then I check that cookie to determine if we should send data to GA and FB.
I originally set this up on a site for called Dahlia, which is a boutique maker of items for Greek Orthodox Weddings and Baptisms.
Here's the code:
I put the following code in the header for all web pages:
<script>
//put in your google analytics tracking id below:
var gaProperty = 'UA-XXXXXXXX-X';
// Disable tracking if the opt-out cookie exists.
var disableStr = 'ga-disable-' + gaProperty;
if (document.cookie.indexOf(disableStr + '=true') > -1) {
window[disableStr] = true;
window['ga-disable-UA-7870337-1'] = true; //This disables the tracking on Weebly too.
} else {
//put in your facebook tracking id below:
fbq('init', 'YYYYYYYYYYYYYYY');
fbq('track', 'PageView');
}
</script>
Be sure to add your GA and FB tracking IDs in the spaces provided. This was originally written for a Weebly (shopping CMS) site. So if you are not on Weebly you can remove the line that mentions weebly.
Then I created a new webpage called "do-not-track" with the following code in the header:
<script>
//put in your own google analytics tracking id below:
var gaProperty = 'UA-XXXXXXXX-X';
var disableStr = 'ga-disable-' + gaProperty;
// Opt-out function
function gaOptout() {
document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';
window[disableStr] = true;
gaOptoutCheck();
}
// Check Opt-out function
function gaOptoutCheck() {
var name = "ga-disable-"+gaProperty+"=";
var ca = document.cookie.split(';');
var found = "false";
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) found = "true";
}
if (found == "true") alert("Cookie is properly installed");
else alert("COOKIE NOT FOUND");
}
</script>
And the following code in the body:
Click here to opt-out of Google and Facebook Analytics
<br><br>
Please visit this page on every computer, laptop, phone, tablet, etc. that you use;
and for all browser you use on each of those devices.
<br><br>
If you ever remove cookies from browser, you will need to repeat this process for that browser.
<br><br><br>
<a href="javascript:gaOptoutCheck()">
Click to check if cookie is set</a>
<br><br>
Here is my full writeup for the Weebly site
Hope this helps somebody!

get the request host variable.
So wrap an if statement around the analytics javascript like this (Ruby-esque pseudocode):
<body>
<shtuff>dfsfsdf</shtuff>
if not (request.host == 'localhost')
#analytics code here
elsif (request.host == the server's ip/domain)
#analytics code here
else
#do nothing
end
</body>

I have a PHP variable set for my local development that gives me a terminal for providing data/feedback etc when I'm working on stuff.
I use XAMPP so that has an env variable for tmp which is the following:
$isLocal = (getenv("tmp") == '\xampp\tmp') ? true : false;
This doesn't exist on my production server because xampp is not being used
if($isLocal){
// do something, eg. load my terminal
}
... Specific to this question:
<?php if(!$isLocal){ ?>
<!-- Insert Google Analytics Script Here -->
<?php } // end google analytics local check ?>

Today, whilst on a different computer than my own, I noticed μBlock Origin for Chrome was blocking Google AdSense by default. After some Googling, I found this article. It notes also μBlock Origin Firefox, μ Adblock for Firefox and Ad Muncher for Windows block AdSense by default. Most other options are listed as being configurable to block AdSense.
This seems to work and is useful because my IP is often dynamic, so the Chrome extension can follow me around as long as I am logged in to Chrome.

Unfortunatelly, it doesn't seem to be possible to exclude localhost from the reporting when using App + Web Properties type of setup:
Displaying Filters for web-only Properties only. Filters can't be applied to App + Web Properties.
For the nextjs web application, especially ones which are using static generation or SSR this would work:
In your document.tsx
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
. . . . .
<body>
<Main />
<NextScript />
{process.env.NODE_ENV === 'production' ? injectAnalytics() : ''}
</body>
</Html>
);
}
}
where injectAnalytics is a function which returns your GA code, for instance:
function injectAnalytics(): React.ReactFragment {
return <>
{/* Global Site Tag (gtag.js) - Google Analytics */}
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
window.gtag = gtag;
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
</>
}

I am using this code to disable google analytics in rails 6 in production.
When admin login I set is_developer cookie to disable google analytics for 1 year.
If admin logout, I do not delete is_developer cookie. So,google analytics will be disabled after admin logout.
You can comment all console.log after testing.
<% if Rails.env.production? %>
<% ga_tracking_id = 'G-36......Y6' %>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= ga_tracking_id %>"></script>
<% if user_signed_in? && current_user.admin? %>
<script>
if(document.cookie.indexOf('is_developer') > -1) {
console.log('gtag:- is_developer cookie already set');
} else {
document.cookie = `is_developer=1; expires=${new Date(new Date().getTime()+1000*60*60*24*365).toGMTString()}; path=/`;
console.log('gtag:- is_developer cookie set for 1 year');
}
</script>
<% end %>
<script>
if(document.cookie.indexOf('is_developer') > -1) {
console.log('gtag:- disabled for developer');
} else {
console.log('gtag:- enabled');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '<%= ga_tracking_id %>');
}
</script>
<% end %>
If you have any suggestions, comment below.

Related

How do I get sorted results from the Google Photos search API?

I'm using the search API for Google Photos documented here. I'd like the results in the response to be sorted from newest to oldest, but by default, the results are sorted from oldest to newest. Is there a way to reverse the sorting?
I believe your goal as follows.
You want to sort the result values from the method of "Method: mediaItems.search".
You want to sort the values from oldest to newest.
Issue and workaround:
Unfortunately, in the current stage, it seems that there is no parameter for sorting the returned values for the the method of "Method: mediaItems.search" in Google Photos API. Also, it seems that such parameter is not existing in the method of "mediaItems.list".
By the way, it was found that when albumId is used in the request body for the method of "Method: mediaItems.search", the returned values are sorted as the ascending order. If you use the albumn ID, I think that your goal can be achieve by this.
On the other hand, when albumId is NOT used in the request body, the returned values are sorted as the descending order. And also, it seems that when filteres is used in the request body, the returned values are sorted as the descending order.
From your question, I thought that in your situation, albumId might be not used. So in this case, as the current workaround, how about sorting the values using a script after the values are retrieved? In this answer, I would like to propose to use the Web Apps created by Google Apps Script as a wrapper API.
Usage:
1. Create new project of Google Apps Script.
Sample script of Web Apps is a Google Apps Script. So please create a project of Google Apps Script.
If you want to directly create it, please access to https://script.new/. In this case, if you are not logged in Google, the log in screen is opened. So please log in to Google. By this, the script editor of Google Apps Script is opened.
2. Linking Cloud Platform Project to Google Apps Script Project.
About this, you can see the detail flow at here.
And also, please enable Google Photos API at API console.
3. Add scope.
In this case, please addt the scope of https://www.googleapis.com/auth/photoslibrary to the manifest file (appsscript.json).
4. Script.
Please copy and paste the following script (Google Apps Script) to the script editor. This script is for the Web Apps. This Web Apps is used as an API.
function doGet(e) {
const key = "sampleKey"; // This is used for using this Web Apps.
try {
if (e.parameter.key != key) throw new Error("Invalid key.");
const albumId = e.parameter.albumId;
const filters = e.parameter.filters;
const sort = e.parameter.sort;
const headers = {"Authorization": "Bearer " + ScriptApp.getOAuthToken()};
const url = "https://photoslibrary.googleapis.com/v1/mediaItems:search";
let mediaItems = [];
let pageToken = "";
const metadata = {pageSize: 100, pageToken: pageToken};
if (albumId) metadata.albumId = albumId;
if (filters) metadata.filters = JSON.parse(filters);
do {
const params = {
method: "post",
headers: headers,
contentType: "application/json",
payload: JSON.stringify(metadata),
}
const res = UrlFetchApp.fetch(url, params);
const obj = JSON.parse(res.getContentText());
mediaItems = mediaItems.concat(obj.mediaItems);
pageToken = obj.nextPageToken || "";
} while (pageToken);
if (mediaItems.length > 0) {
if (sort && sort == "ascending") {
mediaItems.sort((a, b) => new Date(a.mediaMetadata.creationTime) < new Date(b.mediaMetadata.creationTime) ? -1 : 1);
}
return ContentService.createTextOutput(JSON.stringify({values: mediaItems}));
}
return ContentService.createTextOutput(JSON.stringify({error: "No values."}));
} catch(err) {
return ContentService.createTextOutput(JSON.stringify({error: err.message}));
}
}
5. Deploy Web Apps.
The detail information can be seen at the official document.
On the script editor, at the top right of the script editor, please click "click Deploy" -> "New deployment".
Please click "Select type" -> "Web App".
Please input the information about the Web App in the fields under "Deployment configuration".
Please select "Me" for "Execute as".
This is the important of this workaround.
Please select "Anyone" for "Who has access".
In this case, the user is not required to use the access token. So please use this as a test case.
When you want to use the access token, please set it to Anyone with Google account or Only myself. By this, the user can access to the Web Apps using the access token. When you use the access token, please include the scope of https://www.googleapis.com/auth/drive.readonly or https://www.googleapis.com/auth/drive.
Please click "Deploy" button.
When "The Web App requires you to authorize access to your data" is shown, please click "Authorize access".
Automatically open a dialog box of "Authorization required".
Select own account.
Click "Advanced" at "This app isn't verified".
Click "Go to ### project name ###(unsafe)"
Click "Allow" button.
Copy the URL of Web App. It's like https://script.google.com/macros/s/###/exec.
When you modified the Google Apps Script, please redeploy as new version. By this, the modified script is reflected to Web Apps. Please be careful this.
6. Testing.
As the test of this Web Apps, I would like to propose to use the following curl command. Please replace https://script.google.com/macros/s/###/exec with your Web Apps URL.
Simple use:
In this curl command, the result value is returned as the ascending order of oldest to newest.
$ curl -GL -d "key=sampleKey" -d "sort=ascending" https://script.google.com/macros/s/###/exec
Use albumId:
When you want to use the album ID, please use the following curl command.
$ curl -GL -d "albumId=###" -d "key=sampleKey" -d "sort=ascending" https://script.google.com/macros/s/###/exec
In this case, even when -d "sort=ascending" is not used, the result value is returned as the ascending order of oldest to newest.
Use filters:
When you want to use the filters, please use the following curl command.
$ curl -GL -d 'filters={"dateFilter":{"ranges":[{"startDate":{"year":2020},"endDate":{"year":2021}}]}}' -d "key=sampleKey" -d "sort=ascending" https://script.google.com/macros/s/###/exec
In this command, the values of 2020 - 2021 are returned as the ascending order of oldest to newest.
Note:
Although when I searched this at the Google issue tracker, I couldn't find about it. So how about reporting this as the future request? Ref
References:
Method: mediaItems.search
Related thread.
How to use Google Photos API Method: mediaItems.search in Google apps script for a spreadsheet
Google photos api adding photos not working, upload seems to work
Google Apps Scripts: import (upload) media from Google Drive to Google Photos?

Why won't the Google Maps Directions API example in the 'Google Maps' book work for me?

I'm using the Petrousos 'Google Maps' book, and trying to run the example in the CHAPTER17/HTML/Directions Service.html downloaded from the book's website at www.mhprofessional.com at item 0071823026.
I had to adjust the table dimensions to get it to display properly, but otherwise made no changes. I'm running it through Firefox.
I set the origin and destination and clicked "Show Directions", at which point nothing happened.
The event called the following function:
function showDirections() {
var start = document.getElementById("origin").value;
var end = document.getElementById("destination").value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
printDirections(result);
}
});
}
I get as far as the directionsService.route call, but it is apparently not being executed, and status and result are not defined.
I have no idea how to debug this further, not having access to the API code..
Could the syntax of the call in the example be outdated?
I don't have an API key, but I understand it is not necessary, and I have run other examples without one.
Do you old examples still work? If not, then it's because you don't have an API key. Google will shut you down after you surpassed the quota. I believe the quota is at 50 requests per hours.
Google has the most recent documentation (and it's impressively well documented)
https://developers.google.com/maps/documentation/directions/intro#Audience
Also, can you look at what the object returns? If so, that will usually indicate the quote being surpassed. You can do this by setting a breakpoint at the link
if (status == google.maps.DirectionsStatus.OK) {
If you're using Chrome, you can get to the debugger by right-clicking on the page adn choosing 'Inspect Element', then go to sources, find your line of code and click the link number to set a breakpoint.

Google Apps Script login to website with HTTP request

I have a spreadsheet on my Google Drive and I want to download a CSV from another website and put it into my spreadsheet. The problem is that I have to login to the website first, so I need to use some HTTP request to do that.
I have found this site and this. If either of these sites has the answer on it, then I clearly don't understand them enough to figure it out. Could someone help me figure this out? I feel that the second site is especially close to what I need, but I don't understand what it is doing.
To clarify again, I want to login with an HTTP request and then make a call to the same website with a different URL that is the call to get the CSV file.
I have done a lot of this in the past month so I should be able to help you, we are trying to emulate the browsers behaviour here so first you need to use chrome's developer tools(or something similar) and note down the exact things the browser does like the form values posted, the url that is called and so on. The following example shows the general techinique to be used:
The first step is to login to the website and get the session cookie:
var payload =
{
"user_session[email]" : "username",
"user_session[password]" : "password",
};// The actual values of the post variables (like user_session[email]) depends on the site so u need to get it either from the html of the login page or using the developer tools I mentioned.
var options =
{
"method" : "post",
"payload" : payload,
"followRedirects" : false
};
var login = UrlFetchApp.fetch("https://www.website.com/login" , options);
var sessionDetails = login.getAllHeaders()['Set-Cookie'];
We have logged into the website (In order to confirm just log the sessionDetails and match it with the cookies set by chrome). The next step is purely dependent on the website so I will give u a general example
var downloadPayload =
{
"__EVENTTARGET" : 'ctl00$ActionsPlaceHolder$exportDownloadLink1',
};// This is just an example it may or may not be needed, if needed u need to trace the values from the developer tools.
var downloadCsv = UrlFetchApp.fetch("https://www.website.com/",
{"headers" : {"Cookie" : sessionDetails},
"method" : "post",
"payload" : downloadPayload,
});
Logger.log(downloadCsv.getContentText())
The file should now be logged, you can then parse the csv using hte GAS inbuilt function and dump the data in the spreadsheet.
A few points to note:
I have assumed that all form post values are static and can be
hardcoded, in case this is not true then let me know I will give you
a function that can extract values from the html.
Some websites require the browser to send a token value(the value will be present in the html) along with the credentials. In this case you need to extract the values and then post it.

Use of OOcharts api to fetch google analytics data

Hello I am using oocharts plugin to fetch google analytics statistics for my CMS dashboard,
I couldn't understand where I am going wrong?
Here is the default code that I am using of one of the file metric.html to get no of visits
<html>
<head>
</head>
<body>
<h3>With JS</h3>
Visits : <span id='metric'></span>
<h3>With HTML Attributes</h3>
Visits : <span data-oochart='metric' data-oochart-metric='ga:visits' data-oochart-start-date='30d' data-oochart-profile='{{ My Profile Id }}'></span>
<script src='oocharts.js'></script>
<script type="text/javascript">
window.onload = function(){
oo.setAPIKey("{{ My Key }}");
oo.load(function(){
var metric = new oo.Metric("{{ My profile Id }}", "30d");
metric.setMetric("ga:visits");
metric.draw('metric');
document.getElementById('metric').value=metric;
alert(metric);
});
};
</script>
</body>
I understand the full code, but yet I am not able to manipulate data,i.e., I am not able to echo/print this data. Also when i check my firefox console to see all the url are properly called, I get an error of 400 bad request, while calling api.oocharts.com
can someone tell me what should be done in this case?
I just want to echo atleast one data like visit: for my site.
Thanks in advance!
You must wait for a while to take effect. May be their server not updated as soon as you add API Key.
You need to replace {{ profile ID }} with your Google Analytics profile ID. This can be found by logging into analytics, clicking Admin, then taking a look at the URL which will look something like this
'https://www.google.com/analytics/web/?hl=en#management/Settings/a5381475w10244833p10898655/'
The profile ID is the 7+ digit number after p in the URL. In this case, the profile ID is 10898655.
You also need to replace {{ api key }} with your OOCharts API, which you should have generated in the OOCharts admin console using your Google account.

Facebook OAuth login for iframe canvas apps displays a logo image and a Go to Facebook.com caption instead of logging in

I'm trying to set up my (iframe) Facebook application to use OAuth for authentication.
I used the python-sdk from Facebook, but I'm not really satisfied by the result, yet.
The problem is that when I redirect a user that never accessed my application to the login page, my iframe diplays an ugly intermediate page, such as the following one:
If the user clicks on "Go to Facebook.com" link, she is then redirected to the standard "Request for Permission" page.
Is there any way to avoid the first page and lead the user straight to the second one?
This problem happens on the first access for users that haven't granted any permission to my application yet.
The login code is based on the OAuth example in the Python SDK:
class LoginHandler(BaseHandler):
def get(self):
verification_code = self.request.get("code")
args = dict(client_id=FACEBOOK_APP_ID, redirect_uri=self.request.path_url)
if self.request.get("code"):
args["client_secret"] = FACEBOOK_APP_SECRET
args["code"] = self.request.get("code")
raw_response = urllib.urlopen(
"https://graph.facebook.com/oauth/access_token?" +
urllib.urlencode(args)).read()
logging.debug("access_token raw response " + raw_response)
response = cgi.parse_qs(raw_response)
access_token = response["access_token"][-1]
# Download the user profile and cache a local instance of the
# basic profile info
graph = facebook.GraphAPI(access_token)
profile = graph.get_object("me")
user = User.get_by_key_name(profile["id"])
if not user:
user = User(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
firstname=profile["first_name"],
profile_url=profile["link"],
access_token=access_token)
user.put()
elif user.access_token != access_token:
# we already know this user, but we need to update
user.access_token = access_token
user.put()
set_cookie(self.response, "fb_user", str(profile["id"]),
expires=time.time() + 30 * 86400)
self.response.headers["P3P"] = 'CP="IDC CURa ADMa OUR IND PHY ONL COM STA"'
self.redirect("/")
else:
self.redirect(
"https://graph.facebook.com/oauth/authorize?" +
urllib.urlencode(args))
The issue is caused to the code Facebook uses to bust out of iframes. A bug has been filed on Facebook's bugzilla: http://bugs.developers.facebook.net/show_bug.cgi?id=11326
The only known solution to this problem is to do the first redirect to https://graph.facebook.com/oauth/authorize? from the client side (i.e. Via JavaScript), using
<script type='text/javascript'>
top.location.href="https://graph.facebook.com/oauth/authorize?.......
</script>
This can be triggered when the user clicks on some element (e.g. a login button) or whenever a specific page is visited (just include it in the HTML head).
yes, top.location.href should do the trick. If you get the problem that the app breaks out the iframe, make sure you use the canvas PAGE url in your redirect, in stead of canvas url (in your app settings)
This happens, apparently due to a bug in the Facebook side... I found this solution.
<script type="text/javascript">
top.location.href = '<?php echo $loginUrl ?>';
</script>
$loginUrl = your URL
Could work this way:
<script type="text/javascript">
top.location.href = 'http://www.yourappUrl.com';
</script>
always use this code in script tags...
The first page is an error. You absolutely can avoid that page. The problem is likely related to how you are doing the redirects to the login page in the first place. Without a code sample, that is really the best answer I can give.