Hello Analytics example generates 403 error - javascript

I am a "newbie" to the Google Analytics API and I am trying to get the "Hello Analytics" example working.
I followed their steps
to create the test web page but I got no results.
When I go to my web page, I see the title, the "Sign in" button and the text area below where the result should appear. When I press "Sign in", that seems to work; the button changes to say "Signed In". However, no results appear.
I am using FireFox so I right-clicked on the text area and selected "Inspect Element"; this shows this error message:
Object { result: Object, body: "{ "error": { "code": 403, …",
headers: Object, status: 403, statusText: "Forbidden" }
I think this is a permission error but do not know how to correct it.
Here is my file HelloAnalytics.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Analytics Reporting API V4</title>
<meta name="google-signin-client_id" content="959582115031-ardmn5vsir7kbcp0dme4d4n1p45bd649.apps.googleusercontent.com">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
</head>
<body>
<h1>Hello Analytics Reporting API V4</h1>
<p>
<!-- The Sign-in button. This will run `queryReports()` on success. -->
<div class="g-signin2" data-onsuccess="queryReports"></div>
</p>
<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>
<script>
// Replace with your view ID.
var VIEW_ID = '92320289';
// Query the API and print the results to the page.
function queryReports() {
gapi.client.request({
path: '/v4/reports:batchGet',
root: 'https://analyticsreporting.googleapis.com/',
method: 'POST',
body: {
reportRequests: [
{
viewId: VIEW_ID,
dateRanges: [
{
startDate: '7daysAgo',
endDate: 'today'
}
],
metrics: [
{
expression: 'ga:sessions'
}
]
}
]
}
}).then(displayResults, console.error.bind(console));
}
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
}
</script>
<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>
</body>
</html>
I need to understand how to use the Google Analytics API to do simple queries.

FINALLY got it to work!
I was trying to use the API to get data for the Google sample site ("Google Merchandise Store"). I was trying to think of possible reasons for the permission error, and it occurred to me that maybe Google didn't allow Analytics API calls for that web site.
So I went through the effort of setting up my own test web site with Google's Javascript tracking code in it, then defining a new project, enabling the API for it, creating credentials (a client ID) and getting the view ID for my web site. With the new client ID and view ID in my HelloAnalytics.html page, it worked perfectly.
So my guess was correct: Google does NOT permit API calls to get data for its "Google Merchandise Store" sample website. They REALLY should mention this on their "quickstart" page because a "newbie" (like me) wouldn't know that!
I thought I should post my solution because I'm sure that somebody else will run into this problem in the future.
FYI- I have HelloAnalytics.html running on a web server. I am using free web space provided by my ISP.

Related

How to implement Google RecaptchaV2 in Nuxt 3 App

I'm actually trying to implement Google reCaptcha in Nuxt App and I'm currently using "nuxt": "3.0.0-rc.11". I try to add this with nuxt2 or vue3 reCaptcha lib but unfortunately, I ended up with some error.
Anyone knows how I implement Google reCaptcha V2 in nuxt 3 App.
Here's my current implementation.
<template>
<form
action="?"
class="mt-8"
method="POST"
>
<div id="g-recaptcha"></div>
</form>
</template>
<script setup lang="ts">
useHead({
title: 'Contact',
titleTemplate: 'Gears - %s',
viewport: 'width=device-width, initial-scale=1, maximum-scale=1',
charset: 'utf-8',
meta: [
{name: 'description', content: 'Let’s discuss your work together.'}
],
// Here I Inject reCaptcha script using `useHead()` composable
script: [
{
hid: 'recaptcha',
src: 'https://www.google.com/recaptcha/api.js?trustedtypes=true?onload=onloadCallback&render=explicit',
defer: true
}
]
})
const isRecaptchaChecked = ref(false)
const form = reactive({
token: ''
})
function recaptchaCallback(token) {
isRecaptchaChecked.value = grecaptcha && grecaptcha.getResponse().length !== 0;
if (isRecaptchaChecked.value) {
form.token = token
}
}
onMounted(async () => {
await grecaptcha.render('g-recaptcha', {
'sitekey': runtimeConfig.siteKey,
'callback': recaptchaCallback
});
})
</script>
Problem #1 with this implementation
This implementation works fine but It's gave error ReferenceError: grecaptcha is not defined on initial load and if we reload the page the recaptcha works fine and even generate token
Problem #2 with this implementation
As I said this It's gave error ReferenceError: grecaptcha is not defined on initial load and when we reload the page this works fine. Now heading to problem 2, the other problem I face is after getting success recaptcha response If we change the page for example we want to go from /contact to /home the route change on browser URL bar but page is not changed.
Here's the live Website URL
Important Note
Before navigating to contact page please open devtool console and read my two problem and apply them you will understand better about my problem.
Thanks in advance.
ANNOUNCEMENT
I just found a way to implement reCAPTCHA v2 in nuxt3 but before that I want to tell the #nuxtjs/recapthca is not compatible with Nuxt3 and when #nuxtjs/recaptcha is support Nuxt3 then use #nuxt-recaptcha package instead of this solution.
Here's the Solution.

Not a valid origin for the client from Google API Oauth

I'm receiving this error from Google API Oauth:
idpiframe_initialization_failed", details: "Not a valid origin for the client: http://127.0.0.…itelist this origin for your project's client ID
I'm trying to send a request from this local path:
http://127.0.0.1:8887/
And I already added this URL to the Authorized JavaScript origins
section:
This is my code:
<!-- The top of file index.html -->
<html itemscope itemtype="http://schema.org/Article">
<head>
<!-- BEGIN Pre-requisites -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer>
</script>
<!-- END Pre-requisites -->
<!-- Continuing the <head> section -->
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'MY CLIENT ID.apps.googleusercontent.com',
// Scopes to request in addition to 'profile' and 'email'
//scope: 'https://www.google.com/m8/feeds/'
});
});
}
</script>
</head>
<body>
<button id="signinButton">Sign in with Google</button>
<script>
$('#signinButton').click(function() {
// signInCallback defined in step 6.
auth2.grantOfflineAccess().then(signInCallback);
});
</script>
<!-- Last part of BODY element in file index.html -->
<script>
function signInCallback(authResult) {
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
// Send the code to the server
$.ajax({
type: 'POST',
url: 'http://example.com/storeauthcode',
// Always include an `X-Requested-With` header in every AJAX request,
// to protect against CSRF attacks.
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
},
processData: false,
data: authResult['code']
});
} else {
// There was an error.
}
}
</script>
<!-- ... -->
</body>
</html>
How can I fix this?
Reseting Chrome cached solved it for me. Long press on Reload button, then Empty Cache and Hard Reload.
Note: Make sure your Chrome Dev tools panel is open otherwise long press wont work.
I had a very similar issue to yours. I tried to add multiple whitelisted ports from localhost and nothing was working. Ended up deleting the credentials and setting them up again. Must have been a bug on googles end for my setup.
If it's all the same to you, try adding http://localhost:8887 to your authorized JavaScript origins instead. Had that error myself at some point and this fixed it. Know that you will have to use this URL for your request as well event though it translates to http://127.0.0.1:8887/.
I read on several places on the web people use to redo the creation of the credentials to get it to work.
So I did, I created a new credential for the same project and used my new user-id and it worked perfectly... Looks like the edition of the whitelist is a bit flacky...
Nb: I also used localhost instead of 127.0.0.1, IPs are not valid.
I fiddled around for about 10 minutes and then it finally worked when I tried
http://localhost/ in the browser (instead of 127.0.0.1)
Added the url at every place you can do white-lists at:
https://console.developers.google.com/apis/credentials/
I had this same issue; but this is what worked for me:
Open console.developers
Open the project name
Click on the credentials
Under the "name", click on the "web client 1"
Under the "URLs", add "http://localhost:3000"
just my 2 cents.. was able to get it working after deleting and recreating the credentials. Just as suggested above.
In case anyone missed this, next to the save button it does say:
Note: It may take 5 minutes to a few hours for settings to take effect
Waiting fixed this issue for me.
"Not a valid origin for the client" seems to be over-used by Google's API, i.e. it's misleadingly used for authentication errors too.
For people seeing the error, check that the credentials are correct.
(This might explain why it works for some people after re-creating credentials - in some cases, the original credentials might not have been correct).
I solved via adding both http://localhost and http://localhost:8083.
Okay so this is super embarrasing, but for me I was following the docs for the Google Sign-in Web package for a Flutter app, and where it says:
On your web/index.html file, add the following meta tag, somewhere in the head of the document: <meta name="google-signin-client_id" content="YOUR_GOOGLE_SIGN_IN_OAUTH_CLIENT_ID.apps.googleusercontent.com">
I had copied what was listed as my Client ID and pasted it at the beginning and had therefor duplicated the apps.googleusercontent.com portion of the content label in the meta tag. So it might help to make sure you haven't duplicated that!
I just went through all of these solutions before realizing I was putting in
https://localhost:3000
and my dev server was serving up
http://localhost:3000
Stupid, I know, but someone else will probably make the same mistake and perhaps this comment will help them :)
What worked for us was adding a non-localhost domain to the authorized origins. My colleague had his localhost-domains working after adding a non-existing local domain, e.g. http://test-my-app.local.
It might be in case, while you are using same email id for creating client id and for sign-in through webpage

OneSignal hello-world webpage - no notification

I've spent an embarrassingly long time on this seemingly incredibly easy problem with 0 progress. I'm pretty desperate at this point, so if anybody could review the short example I've written, I would greatly appreciate it.
What I'm trying to do: send a push notification using OneSignal's Web Push SDK.
Files in ~/Desktop/OneSignal-Browser-Example:
index.html
<head>
<title>OneSignal Example</title>
<link rel="manifest" href="/manifest.json">
<script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async></script>
<script>
var OneSignal = window.OneSignal || [];
OneSignal.push(["init", {
appId: "518e60ef-8b73-4852-8172-61cb170dce00",
autoRegister: true,
notifyButton: {
enable: true /* Set to false to hide */
}
}]);
console.log("Test");
</script>
<h1>LOADED</h1>
</head>
manifest.json
{
"name": "OneSignal Example",
"short_name": "OneSignalExample",
"start_url": "/",
"display": "standalone",
"gcm_sender_id": "482941778795"
}
OneSignalSDKWorker.js
importScripts('https://cdn.onesignal.com/sdks/OneSignalSDK.js');
OneSignalSDKUpdaterWorker.js
importScripts('https://cdn.onesignal.com/sdks/OneSignalSDK.js');
cert.pem
key.pem
I launched Google Chrome with /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors, and set up a https server on port 8081 with http-server --ssl --p 8081 ~/Desktop/OneSignal-Browser-Example.
Attached is a screenshot of the trace log.
I think we were able to help you out over our support channel to solve the issue.
The issue was a specific configuration mismatch: uPaymeiFixit had modified the manifest.json file's gcm_sender_id property to an incorrect value; he subscribed after this change and registered his user with a mismatched GCM Sender ID which prevented notifications from being able to send even though everything else was correct.
The solution to this issue was to:
Correct the gcm_sender_id value.
Reset his site data and cache to test again as a new user.
He was able to receive a notification right after these changes.

Saving and restoring current view state of a Tableau graph through javascript API

The problem:
How can I store - and then later retrieve - the custom state of a Tableau view through the javascript-API?
Description:
I am working on a site where we currently allow any user to collaborate a set of Tableau views into a PowerPoint-like online presentation for later use. In our current implementation, the state of the Tableau graphs are not stored, and the user therefore has to apply his or hers desired filter, select worksheets etc. while holding the presentation - every time. This is what we now would like to avoid.
The easiest solution for this would be to store and retrieve one of the "Share"-links accessed through the bottom bar interface; these links contains the state of the current view, but so far, we have not been able to do this: firstly, due to domain issues, we cannot simply fetch the Share-links from the embed-code iframe; and secondly, the API-method workbook.getUrl() does not seem to include the state of the current view.
I am currenty looking into the workbook.rememberCustomViewAsync(name) and workbook.showCustomViewAsync(name) methods, which seem like a possible solution. However, I cannot seem to get any sensible results from either of these two methods, as they both end up giving obscure, non-informative 500 errors when run.
An example file, and the errors:
To better illustrate this issue, I have created a minimal demo (snippet below) that attempts to use the second method described above. When opened in Google Chrome, neither of the two buttons ('save state' and 'retrieve state') work for me, and the following errors can be seen in the Developer Tools (the http response message and developer console output, respectively):
Http response:
<br>
2015-11-11 16:14:17.916
(VkNpWQrCQaIAACQo2YYAAAPi,0,0)
Console error:
POST http://public.tableau.com/vizql/w/Book6_426/v/YRKE/save_customized_view/sessions/208A699D34E14708A2268AA10A827C99-0:0 500 (Internal Server Error)
Does anyone know how I can solve this issue, either by making the provided code example work (the second method described), or through any other means? Any help would be appreciated!
PS: The snippet simulator here will cause a Access-Control-Allow-Origin error. The file has also been published here.
<html>
<head>
<title>A simple Tableau API demo</title>
<!--script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!--script type="text/javascript" src="https://online.tableau.com/javascripts/api/tableau_v8.js"></script-->
<script type="text/javascript" src="https://online.tableau.com/javascripts/api/tableau-2.min.js "></script>
</head>
<body>
<H2>Custom view storage demo</H2>
<button id="remember-button">
Remember state 'test'
</button>
<button id="retrieve-button">
Retrieve state 'test'
</button>
<div id="viz-placeholder" style="width: 1000px; height: 1000px; display: block;"></div>
<script>
// Render tableau graph
function initializeViz() {
var placeholderDiv = document.getElementById("viz-placeholder");
var url = "https://public.tableau.com/views/Book6_426/YRKE";
var options = {
width: placeholderDiv.offsetWidth,
height: placeholderDiv.offsetHeight,
hideTabs: true,
hideToolbar: true,
onFirstInteractive: function() {
workbook = viz.getWorkbook();
activeSheet = workbook.getActiveSheet();
}
};
viz = new tableau.Viz(placeholderDiv, url, options);
}
$(initializeViz)
// Assign and set up button actions for storing and retrieving the custom view
var customViewName = "test";
$('#remember-button').click(function() {
console.log("Remembering: ", customViewName);
// Try to save state, or print error
viz.getWorkbook().rememberCustomViewAsync(customViewName).otherwise(function(err) {
console.log("An error occured:");
console.log(err);
});
});
$('#retrieve-button').click(function() {
console.log("Retrieving: ", customViewName);
// Try to retrieve state, or print error
viz.getWorkbook().showCustomViewAsync(customViewName).otherwise(function(err) {
console.log("An error occured:");
console.log(err);
});
});
</script>
</body>
</html>
Okey, so I have been in contact with Tableau Customer Support, and they seem to have found the issue.
Apparently, certain elements of the javascript-API is only available for Tableau Online and Tableau Server - not Tableau Public.
In other words, the function workbook.rememberCustomViewAsync('customViewName') is not supported for graphs hosted by Tableau Public - such as the one used in the example above (https://public.tableau.com/views/...).

gapi.auth javascript commands are not executed properly

I am trying to follow the sample example from Google's developer tutorial
using updated chrome (version 38.0)
But seems like the gapi.auth functions never reached to the their callbacks
Here is a code example that demonstrate it:
<!doctype html>
<html>
<head>
<title>Google API Client test</title>
</head>
<body>
here will be the use of Oauth 2.0
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
googleApiClientReady = function() {
window.setTimeout(checkAuth, 1);
}
function checkAuth() {
gapi.auth.authorize({
client_id: 'XXX',
scope: 'https://www.googleapis.com/auth/youtube',
immediate: true
}, handleAuthResult);
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
alert('gapi.auth return successfully');
} else {
alert('gapi.auth return with error');
}
}
</script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</body>
</html>
When I run the above html+JS file- none of the 2 optional alerts of 'HandleAuthResult' are displayed on screen at all - meaning that this function is not called back by 'gapi.auth.authorize'
Did anyone manage to use this library properly?
First of all you need to check if chrome has blocked your popup. It's because popup-opening code is not in on-click handler.
Then you should open chrome's developer console and check "Console" tab for errors.
Also you should specify your domain name and port where your page is located in Google Developer Console like this:
I was able to login into google and receive successful callback
using your code but only after removing "immediate: true" option.
I dont know why but i was getting "immediate_failed" error.

Categories

Resources