質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

Q&A

3回答

358閲覧

javascript 関数の呼び出し方

4glte

総合スコア4

JavaScript

JavaScriptは、プログラミング言語のひとつです。ネットスケープコミュニケーションズで開発されました。 開発当初はLiveScriptと呼ばれていましたが、業務提携していたサン・マイクロシステムズが開発したJavaが脚光を浴びていたことから、JavaScriptと改名されました。 動きのあるWebページを作ることを目的に開発されたもので、主要なWebブラウザのほとんどに搭載されています。

0グッド

0クリップ

投稿2020/09/04 05:00

前提・実現したいこと

超初心者です。
現在、Googla analyticsのデータを引っ張てくるということを実現しようとしてます。
https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-js?hl=ja
を参考にしています。
データ自体は引っ張ることに成功したのですが、
関数を起動させる方法を変更しようとしたところうまくいかなくなってしまいました。
具体的には、ページを読み込んだ時に動作させたいです。

発生している問題・エラーメッセージ

GAconnect.js:20 Uncaught TypeError: Cannot read property 'authorize' of undefined at authorize (GAconnect.js:20) at GAconnect.js:133

参考元ソースコード```javascript

一部省略しています。

function authorize(event) { // Handles the authorization flow. // `immediate` should be false when invoked from the button click. var useImmdiate = event ? false : true; var authData = { client_id: CLIENT_ID, scope: SCOPES, immediate: useImmdiate }; gapi.auth.authorize(authData, function(response) { var authButton = document.getElementById('auth-button'); if (response.error) { authButton.hidden = false; } else { authButton.hidden = true; queryAccounts(); } }); } document.getElementById('auth-button').addEventListener('click', authorize);

自身で修正したソースコード```javascript

function authorize(event) { // Handles the authorization flow. // `immediate` should be false when invoked from the button click. var useImmdiate = event ? false : true; var authData = { client_id: CLIENT_ID, scope: SCOPES, immediate: useImmdiate }; gapi.auth.authorize(authData, function(response) { var authButton = document.getElementById('auth-button'); if (response.error) { authButton.hidden = false; } else { authButton.hidden = true; queryAccounts(); } }); } authorize('click');

試したこと

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Lhankor_Mhy

2020/09/04 05:10

<script src="https://apis.google.com/js/client.js"></script> と authorize('click'); の、ソースコード上での位置関係を知りたいです。 APIが読み込まれる前に実行されているのではないか、ということを疑っています。
4glte

2020/09/04 05:38

ご回答ありがとうございます! htmlにて以下のようにコードしています。 GAconnect.js が上記のコードになります。 <script src="https://apis.google.com/js/client.js?onload=authorize"></script> <script type="text/javascript" src="GAconnect.js"></script>
4glte

2020/09/04 05:42

私は、scriptは上から順に実行されていくと認識されているのですが、そうではないということなのでしょうか・・・?
Lhankor_Mhy

2020/09/04 06:09 編集

GAconnect.js は ご提示のスクリプトで全てですか? そうだとすると、client.js が非同期処理をしている場合、gapiが準備される前に実行される可能性があります。コールバックなどを使って処理する必要があるでしょう。
4glte

2020/09/04 08:09

// Replace with your client ID from the developer console. var CLIENT_ID = '192666226904-8tk8d97kmvk2e4bm4gfbjs1iddjobpmm.apps.googleusercontent.com'; // Set authorized scope. var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']; var GAdata; function authorize(event) { // Handles the authorization flow. // `immediate` should be false when invoked from the button click. var useImmdiate = event ? false : true; var authData = { client_id: CLIENT_ID, scope: SCOPES, immediate: useImmdiate }; gapi.auth.authorize(authData, function(response) { var authButton = document.getElementById('auth-button'); if (response.error) { authButton.hidden = false; } else { authButton.hidden = true; queryAccounts(); } }); } function queryAccounts() { // Load the Google Analytics client library. gapi.client.load('analytics', 'v3').then(function() { // Get a list of all Google Analytics accounts for this user gapi.client.analytics.management.accounts.list().then(handleAccounts); }); } function handleAccounts(response) { // Handles the response from the accounts list method. if (response.result.items && response.result.items.length) { // Get the first Google Analytics account. var firstAccountId = response.result.items[0].id; // Query for properties. queryProperties(firstAccountId); } else { console.log('No accounts found for this user.'); } } function queryProperties(accountId) { // Get a list of all the properties for the account. gapi.client.analytics.management.webproperties.list( {'accountId': accountId}) .then(handleProperties) .then(null, function(err) { // Log any errors. console.log(err); }); } function handleProperties(response) { // Handles the response from the webproperties list method. if (response.result.items && response.result.items.length) { // Get the first Google Analytics account var firstAccountId = response.result.items[0].accountId; // Get the first property ID var firstPropertyId = response.result.items[0].id; // Query for Views (Profiles). queryProfiles(firstAccountId, firstPropertyId); } else { console.log('No properties found for this user.'); } } function queryProfiles(accountId, propertyId) { // Get a list of all Views (Profiles) for the first property // of the first Account. gapi.client.analytics.management.profiles.list({ 'accountId': accountId, 'webPropertyId': propertyId }) .then(handleProfiles) .then(null, function(err) { // Log any errors. console.log(err); }); } function handleProfiles(response) { // Handles the response from the profiles list method. if (response.result.items && response.result.items.length) { // Get the first View (Profile) ID. var firstProfileId = response.result.items[0].id; // Query the Core Reporting API. queryCoreReportingApi(firstProfileId); } else { console.log('No views (profiles) found for this user.'); } } function queryCoreReportingApi(profileId) { // Query the Core Reporting API for the number sessions for // the past seven days. gapi.client.analytics.data.ga.get({ 'ids': 'ga:' + profileId, 'start-date': '7daysAgo', 'end-date': 'today', 'dimensions': 'ga:eventCategory,ga:eventAction,ga:eventLabel', 'metrics': 'ga:totalEvents' }) .then(function(response) { formattedJson = JSON.stringify(response.result, null, 2); GAdata = JSON.parse(formattedJson); console.log(GAdata.rows); }) .then(null, function(err) { // Log any errors. console.log(err); }); } // Add an event listener to the 'auth-button'. console.log('test'); window.onload = authorize('click'); /* document.addEventListener('DOMContentLoaded', () => { iframe = document.getElementById('showcase_iframe'); iframe.addEventListener('load', authorize, true); }); */ // document.getElementById('js-popup').addEventListener('click', authorize);
4glte

2020/09/04 08:09

これが全文になります・・・
Lhankor_Mhy

2020/09/04 08:32

うーん、なるほど。 window.onloadで実行してもダメなのですね…… そうすると、私ではお役に立てなさそうです。
guest

回答3

0

'authorize' of undefined

ですから呼び出し元の「gapi.auth」がきちんとつかめてないのでしょう

投稿2020/09/04 05:05

yambejp

総合スコア114572

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

4glte

2020/09/04 05:42

回答ありがとうございます! 皆さん同じことを指摘されているように、gapi.authが読み込まれる前に実行されてしまっているのですね
guest

0

具体的には、ページを読み込んだ時に動作させたいです。

Google APIが読み込まれる前に実行しようとするとうまくいきません。「Google APIが読み込まれたタイミングで実行する」ような機能があれば、それを活用するのが適切です。

投稿2020/09/04 05:03

maisumakun

総合スコア145121

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

4glte

2020/09/04 05:57

ご回答ありがとうございます! 補足に記載したのですが、 <script src="https://apis.google.com/js/client.js?onload=authorize"></script> <script type="text/javascript" src="GAconnect.js"></script> なぜ、上のスクリプトの処理が終了する前に、下のスクリプトを先に実行してしまったりするのでしょうか・・・?? よろしければ教えてください・・・
guest

0

参考元にしていたページのHTML中の

<script src="https://apis.google.com/js/client.js?onload=authorize"></script>

の読み込みが完了する前にgapi.auth.authorizeを実行しようとしてエラーになっています。
読み込み後に実行するようにしましょう。
方法はいろいろありますが、下記が参考になります。

投稿2020/09/04 05:34

nekoniki

総合スコア2409

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問