Google Analytics嵌入示例无法运行问题求助
Troubleshooting Your Google Analytics Embed API Implementation
First off, I feel your pain—spending hours on an official example that won’t run is super frustrating. Let’s break down the issues and fixes step by step:
1. Critical Issue: Truncated Code
Looking at your provided HTML, the renderYearOverYearChart function is cut off mid-way through defining the datasets. This will definitely cause syntax errors that break the entire script. I’ve filled in the missing parts based on Google’s official Embed API example below.
2. Other Common Troubleshooting Steps
Even after fixing the truncated code, here are key things to check:
- Browser Console Errors: Press F12 to open DevTools and go to the Console tab. Syntax errors, missing files, or API authorization issues will show up here—this is the first place to look.
- Local File Paths: Your scripts like
/public/javascript/embed-api/components/view-selector2.jsmight not load if you’re running the page directly from your local filesystem (file://). Either run a local web server (e.g.,python -m http.server) or use hosted versions of the Embed API components (I’ve swapped these in the corrected code below). - Client ID Setup:
- Ensure your client ID is linked to a project where the Google Analytics Reporting API v4 is enabled (check Google Cloud Console).
- Add yourself as a test user in the OAuth consent screen (required for testing if the app isn’t published).
- Verify authorized JavaScript origins include your testing domain (e.g.,
http://localhost:8080).
- Outdated Libraries: You’re using old versions of Chart.js (1.0.2) and Moment.js (2.10.2). While the example relies on these versions, if you still have issues, try updating to newer releases (note: you’ll need to adjust chart code slightly for newer Chart.js versions).
3. Corrected Full Code Snippet
Here’s the complete, fixed version of your HTML code with all missing functions and corrected paths:
<!DOCTYPE html> <html> <head> <title>GA Embed API Demo</title> <script> (function(w,d,s,g,js,fs){ g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}}; js=d.createElement(s);fs=d.getElementsByTagName(s)[0]; js.src='https://apis.google.com/js/platform.js'; fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');}; }(window,document,'script')); </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script> <!-- Hosted Embed API components to avoid local path issues --> <script src="https://cdn.jsdelivr.net/npm/@google-analytics/embed-api@1.3.0/dist/components/view-selector2.js"></script> <script src="https://cdn.jsdelivr.net/npm/@google-analytics/embed-api@1.3.0/dist/components/date-range-selector.js"></script> <script src="https://cdn.jsdelivr.net/npm/@google-analytics/embed-api@1.3.0/dist/components/active-users.js"></script> <link rel="stylesheet" href="/public/css/chartjs-visualizations.css"> </head> <body> <div id="embed-api-auth-container"></div> <div id="view-selector-container"></div> <h1 id="view-name"></h1> <div id="active-users-container"></div> <div id="chart-1-container"></div> <div id="legend-1-container"></div> <div id="chart-2-container"></div> <div id="legend-2-container"></div> <div id="chart-3-container"></div> <div id="legend-3-container"></div> <div id="chart-4-container"></div> <div id="legend-4-container"></div> <script> gapi.analytics.ready(function() { gapi.analytics.auth.authorize({ container: 'embed-api-auth-container', clientid: '1049955524348-656m95v1jedr07guiunt7e6h7quv1esl.apps.googleusercontent.com' }); var activeUsers = new gapi.analytics.ext.ActiveUsers({ container: 'active-users-container', pollingInterval: 5 }); activeUsers.once('success', function() { var element = this.container.firstChild; var timeout; this.on('change', function(data) { var element = this.container.firstChild; var animationClass = data.delta > 0 ? 'is-increasing' : 'is-decreasing'; element.className += (' ' + animationClass); clearTimeout(timeout); timeout = setTimeout(function() { element.className = element.className.replace(/ is-(increasing|decreasing)/g, ''); }, 3000); }); }); var viewSelector = new gapi.analytics.ext.ViewSelector2({ container: 'view-selector-container', }).execute(); viewSelector.on('viewChange', function(data) { var title = document.getElementById('view-name'); title.textContent = data.property.name + ' (' + data.view.name + ')'; activeUsers.set(data).execute(); renderWeekOverWeekChart(data.ids); renderYearOverYearChart(data.ids); renderTopBrowsersChart(data.ids); renderTopCountriesChart(data.ids); }); function renderWeekOverWeekChart(ids) { var now = moment(); var thisWeek = query({ 'ids': ids, 'dimensions': 'ga:date,ga:nthDay', 'metrics': 'ga:sessions', 'start-date': moment(now).subtract(1, 'day').day(0).format('YYYY-MM-DD'), 'end-date': moment(now).format('YYYY-MM-DD') }); var lastWeek = query({ 'ids': ids, 'dimensions': 'ga:date,ga:nthDay', 'metrics': 'ga:sessions', 'start-date': moment(now).subtract(1, 'day').day(0).subtract(1, 'week') .format('YYYY-MM-DD'), 'end-date': moment(now).subtract(1, 'day').day(6).subtract(1, 'week') .format('YYYY-MM-DD') }); Promise.all([thisWeek, lastWeek]).then(function(results) { var data1 = results[0].rows.map(function(row) { return +row[2]; }); var data2 = results[1].rows.map(function(row) { return +row[2]; }); var labels = results[1].rows.map(function(row) { return +row[0]; }); labels = labels.map(function(label) { return moment(label, 'YYYYMMDD').format('ddd'); }); var data = { labels : labels, datasets : [ { label: 'Last Week', fillColor : 'rgba(220,220,220,0.5)', strokeColor : 'rgba(220,220,220,1)', pointColor : 'rgba(220,220,220,1)', pointStrokeColor : '#fff', data : data2 }, { label: 'This Week', fillColor : 'rgba(151,187,205,0.5)', strokeColor : 'rgba(151,187,205,1)', pointColor : 'rgba(151,187,205,1)', pointStrokeColor : '#fff', data : data1 } ] }; new Chart(makeCanvas('chart-1-container')).Line(data); generateLegend('legend-1-container', data.datasets); }); } function renderYearOverYearChart(ids) { var now = moment(); var thisYear = query({ 'ids': ids, 'dimensions': 'ga:month,ga:nthMonth', 'metrics': 'ga:users', 'start-date': moment(now).date(1).month(0).format('YYYY-MM-DD'), 'end-date': moment(now).format('YYYY-MM-DD') }); var lastYear = query({ 'ids': ids, 'dimensions': 'ga:month,ga:nthMonth', 'metrics': 'ga:users', 'start-date': moment(now).subtract(1, 'year').date(1).month(0) .format('YYYY-MM-DD'), 'end-date': moment(now).date(1).month(0).subtract(1, 'day') .format('YYYY-MM-DD') }); Promise.all([thisYear, lastYear]).then(function(results) { var data1 = results[0].rows.map(function(row) { return +row[2]; }); var data2 = results[1].rows.map(function(row) { return +row[2]; }); var labels = ['Jan','Feb','Mar','Apr','May','Jun', 'Jul','Aug','Sep','Oct','Nov','Dec']; for (var i = 0, len = labels.length; i < len; i++) { if (data1[i] === undefined) data1[i] = null; if (data2[i] === undefined) data2[i] = null; } var data = { labels : labels, datasets : [ { label: 'Last Year', fillColor : 'rgba(220,220,220,0.5)', strokeColor : 'rgba(220,220,220,1)', pointColor : 'rgba(220,220,220,1)', pointStrokeColor : '#fff', data : data2 }, { label: 'This Year', fillColor : 'rgba(151,187,205,0.5)', strokeColor : 'rgba(151,187,205,1)', pointColor : 'rgba(151,187,205,1)', pointStrokeColor : '#fff', data : data1 } ] }; new Chart(makeCanvas('chart-2-container')).Line(data); generateLegend('legend-2-container', data.datasets); }); } function renderTopBrowsersChart(ids) { query({ 'ids': ids, 'dimensions': 'ga:browser', 'metrics': 'ga:sessions', 'sort': '-ga:sessions', 'max-results': 5 }).then(function(response) { var data = []; var labels = []; response.rows.forEach(function(row) { labels.push(row[0]); data.push(+row[1]); }); var chartData = { labels: labels, datasets: [{ label: 'Sessions', fillColor: 'rgba(220,220,220,0.5)', strokeColor: 'rgba(220,220,220,1)', data: data }] }; new Chart(makeCanvas('chart-3-container')).Pie(chartData); generateLegend('legend-3-container', chartData.datasets); }); } function renderTopCountriesChart(ids) { query({ 'ids': ids, 'dimensions': 'ga:country', 'metrics': 'ga:sessions', 'sort': '-ga:sessions', 'max-results': 5 }).then(function(response) { var data = []; var labels = []; response.rows.forEach(function(row) { labels.push(row[0]); data.push(+row[1]); }); var chartData = { labels: labels, datasets: [{ label: 'Sessions', fillColor: 'rgba(151,187,205,0.5)', strokeColor: 'rgba(151,187,205,1)', data: data }] }; new Chart(makeCanvas('chart-4-container')).Pie(chartData); generateLegend('legend-4-container', chartData.datasets); }); } function query(params) { return new Promise(function(resolve, reject) { gapi.client.request({ path: '/analytics/v3/data/ga', params: params }).then(function(response) { resolve(response.result); }, function(err) { reject(err); }); }); } function makeCanvas(id) { var container = document.getElementById(id); var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); container.innerHTML = ''; canvas.width = container.offsetWidth; canvas.height = container.offsetHeight; container.appendChild(canvas); return ctx; } function generateLegend(id, datasets) { var legend = document.getElementById(id); legend.innerHTML = datasets.map(function(dataset) { return '<div><span style="background-color:' + dataset.fillColor + '"></span>' + dataset.label + '</div>'; }).join(''); } }); </script> </body> </html>
Final Tips
- Start with checking the browser console for errors—it will pinpoint exactly where the problem lies (syntax, missing files, auth issues).
- If you’re still stuck, share the error messages from the console along with details about your setup (local vs. hosted server, API enablement status).
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

