如何使用 javascript 代码在 google 分析中创建新的 属性

How to create new property in google analytics using javascript code

这是我第一次使用分析 api 创建新的 属性

我从这里得到了下面的代码 developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/webproperties/insert

window.onload = function insertProperty() {
  var request = gapi.client.analytics.management.webproperties.insert(
    {
      'accountId': '123456789',
      'resource': {
        'websiteUrl': 'http://www.examplepetstore.com',
        'name': 'Example Store'
      }
    });
  request.execute(function (response) { console.log(response);});
}
<script src="https://apis.google.com/js/api.js"></script>

当我 运行 具有有效帐户 ID 的代码时:'123456789'

我遇到了这个错误

未捕获类型错误:无法在 insertProperty

处读取未定义的属性(读取 'analytics')

我应该如何使用此代码创建新的 属性

下面的代码是授权码和rest码的设置

  // Replace with your client ID from the developer console.
  var CLIENT_ID = '';

  // Set authorized scope.
  var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];


  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',
    'metrics': 'ga:sessions'
  })
  .then(function(response) {
    var formattedJson = JSON.stringify(response.result, null, 2);
    document.getElementById('query-output').value = formattedJson;
  })
  .then(null, function(err) {
      // Log any errors.
      console.log(err);
  });
}

  // Add an event listener to the 'auth-button'.
  document.getElementById('auth-button').addEventListener('click', authorize);
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello Analytics - A quickstart guide for JavaScript</title>
</head>
<body>

<button id="auth-button" hidden>Authorize</button>

<h1>Hello Analytics</h1>

<textarea cols="80" rows="20" id="query-output"></textarea>


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

</body>
</html>
是的,当我点击授权时,我收到了这个错误{error: {code: 403, message: "Request had insufficient authentication scopes.",…}}

不知道为什么..?

The developer hasn’t given you access to this app. It’s currently being tested and it hasn’t been verified by Google

问题是您的项目仍在测试中,您需要添加您想要授予测试您应用程序权限的用户。

转到 google 云控制台 在同意屏幕下查找显示“添加用户”的按钮,将您尝试使用的用户的电子邮件添加到 运行 应用程序。

了解 属性、帐户和 Google 分析中的视图 您的 Analytics 配置文件由 3 个不同的部分组成。它们是帐户、属性 和视图(如果您使用的是 Universal Analytics)。

以下是每一个的详细介绍:

帐户:您应该至少有一个帐户来访问分析报告。 属性:属性 可以是您希望在 Google Analytics 中跟踪的网站或移动应用程序,并且具有唯一的跟踪 ID。 视图:如果您使用的是 Universal Analytics,则视图是报告的访问点。例如,在 属性 中,您可以有不同的视图来查看您网站的所有数据,仅查看特定子域,如 blog.example.com,或仅查看 Google 广告流量。 Google Analytics 4.

中不存在视图