Add view count to webpage from Google Analytics

五迷三道 提交于 2020-01-16 19:38:28

问题


I am trying to create a view count feature for a webpage. To do this, I created a new property and generated a tracking id from Google Analytics.

Is there a way I can use the page vists data from there and display it on the same page that I am tracking?


回答1:


You can, but since GA APIs are authenticated, you will need to handle that authentication one way or another.

You have basically 3 options:

  • User doing OAuth: by default you would need to implement the OAuth flow like the Query Explorer is doing, which is obviously not adequate if the counter is meant to be public, as visitors won't have the appropriate GA permissions to get data from that property
  • Pre generated access token: you can generate the access token manually, and use that token to make the requests: https://developers.google.com/analytics/devguides/reporting/embed/v1/component-reference#auth-options

serverAuth.access_token Type: string

If you already have a valid access token, you can pass it to the authorize method directly and the user will not be prompted to authorize. For details on how to retrieve an access token, see the OAuth 2.0 documentation.

  • Middleware: you can use a tool to pull data from the GA API and then query data from that tool. For instance you can:
    1. Use the GA add-on to pull your data to a Google Sheet
    2. Import that data into another Google Sheet with IMPORTRANGE
    3. Publish the Google Sheet from 2 so it's publicly readable via API (for instance as CSV). You will be provided with a URL that looks like https://docs.google.com/spreadsheets/d/e/{some-uid}/pub?gid=0&single=true&output=csv
    4. Fetch data from that URL from the website (eg with jQuery)

Note: you probably don't have to do step 2 if you're careful, and can publish as CSV your sheet from steo 1 directly: since it's a CSV export, people cannot get to the original spreadsheet so no security risk. But just to be on the safe side (eg you could publish the whole spreadsheet by mistake), I would do step 2.

As for which middleware you want to use, there's probably an infinite number of options :)



来源:https://stackoverflow.com/questions/50436366/add-view-count-to-webpage-from-google-analytics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!