ตัวอย่างโค้ด JavaScript
จัดทุกอย่างให้เป็นระเบียบอยู่เสมอด้วยคอลเล็กชัน
บันทึกและจัดหมวดหมู่เนื้อหาตามค่ากำหนดของคุณ
ตัวอย่างโค้ดด้านล่างใช้ไลบรารีของไคลเอ็นต์ Google APIs สำหรับ JavaScript คุณดาวน์โหลดตัวอย่างนี้ได้จากโฟลเดอร์ javascript
ของที่เก็บตัวอย่างโค้ดของ YouTube API ใน GitHub
โค้ดจะขอสิทธิ์จากผู้ใช้เพื่อเข้าถึงขอบเขต https://www.googleapis.com/auth/yt-analytics.readonly
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/yt-analytics.readonly"})
...
แอปพลิเคชันของคุณอาจต้องขอสิทธิ์เข้าถึงขอบเขตอื่นๆ ด้วย ตัวอย่างเช่น แอปพลิเคชันที่เรียกใช้ YouTube Analytics API และ YouTube Data API อาจต้องให้ผู้ใช้ให้สิทธิ์เข้าถึงบัญชี YouTube ของตนด้วย ภาพรวมการให้สิทธิ์จะระบุขอบเขตที่มักใช้ในแอปพลิเคชันที่เรียกใช้ YouTube Analytics API
เรียกข้อมูลสถิติช่องรายวัน
ตัวอย่างนี้เรียกใช้ YouTube Analytics API เพื่อดึงข้อมูลยอดดูรายวันและเมตริกอื่นๆ สำหรับช่องของผู้ใช้ที่ให้สิทธิ์ในปีปฏิทิน 2017 ตัวอย่างใช้ไลบรารีของไคลเอ็นต์ JavaScript ของ Google APIs
ตั้งค่าข้อมูลเข้าสู่ระบบการให้สิทธิ์
ก่อนเรียกใช้ตัวอย่างนี้ในเครื่องเป็นครั้งแรก คุณต้องตั้งค่าข้อมูลเข้าสู่ระบบการให้สิทธิ์สำหรับโปรเจ็กต์โดยทำดังนี้
- สร้างหรือเลือกโปรเจ็กต์ในคอนโซล Google API
- เปิดใช้ YouTube Analytics API สำหรับโปรเจ็กต์
- ที่ด้านบนของหน้าข้อมูลเข้าสู่ระบบ ให้เลือกแท็บหน้าจอขอความยินยอม OAuth เลือกอีเมล ป้อนชื่อผลิตภัณฑ์หากยังไม่ได้ตั้งค่า แล้วคลิกปุ่มบันทึก
- ในหน้าข้อมูลเข้าสู่ระบบ ให้คลิกปุ่มสร้างข้อมูลเข้าสู่ระบบ แล้วเลือกรหัสไคลเอ็นต์ Oauth
- เลือกประเภทแอปพลิเคชันเป็นเว็บแอปพลิเคชัน
- ในช่องต้นทาง JavaScript ที่ได้รับอนุญาต ให้ป้อน URL ที่คุณจะใช้แสดงตัวอย่างโค้ด เช่น คุณอาจใช้
http://localhost:8000
หรือ http://yourserver.example.com
คุณเว้นช่อง URI การเปลี่ยนเส้นทางที่ได้รับอนุญาตว่างไว้ได้
- คลิกปุ่มสร้างเพื่อสร้างข้อมูลเข้าสู่ระบบให้เสร็จสมบูรณ์
- ก่อนปิดกล่องโต้ตอบ ให้คัดลอกรหัสไคลเอ็นต์ ซึ่งคุณจะต้องใส่ลงในตัวอย่างโค้ด
ทำสำเนาตัวอย่างในเครื่อง
จากนั้นบันทึกตัวอย่างลงในไฟล์ในเครื่อง ในตัวอย่าง ให้ค้นหาบรรทัดต่อไปนี้ แล้วแทนที่ YOUR_CLIENT_ID ด้วยรหัสไคลเอ็นต์ที่คุณได้รับเมื่อตั้งค่าข้อมูลเข้าสู่ระบบการให้สิทธิ์
gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});
เรียกใช้โค้ด
ตอนนี้คุณพร้อมที่จะทดสอบตัวอย่างแล้ว โดยทำดังนี้
- เปิดไฟล์ในเครื่องจากเว็บเบราว์เซอร์ แล้วเปิดคอนโซลการแก้ไขข้อบกพร่องในเบราว์เซอร์ คุณควรเห็นหน้าเว็บที่แสดงปุ่ม 2 ปุ่ม
- คลิกปุ่มให้สิทธิ์และโหลดเพื่อเปิดขั้นตอนการให้สิทธิ์ผู้ใช้ หากให้สิทธิ์แอปในการดึงข้อมูลช่อง คุณควรเห็นบรรทัดต่อไปนี้พิมพ์ลงในคอนโซลในเบราว์เซอร์
Sign-in successful
GAPI client loaded for API
- หากเห็นข้อความแสดงข้อผิดพลาดแทนบรรทัดด้านบน ให้ยืนยันว่าคุณกำลังโหลดสคริปต์จาก URI การเปลี่ยนเส้นทางที่ได้รับอนุญาตซึ่งคุณตั้งค่าไว้สำหรับโปรเจ็กต์ และคุณได้ใส่รหัสไคลเอ็นต์ลงในโค้ดตามที่อธิบายไว้ข้างต้น
- คลิกปุ่มเรียกใช้เพื่อเรียก API คุณควรเห็นออบเจ็กต์
response
พิมพ์ไปยังคอนโซลในเบราว์เซอร์ ในออบเจ็กต์นั้น พร็อพเพอร์ตี้ result
จะแมปกับออบเจ็กต์ที่มีข้อมูล API
โค้ดตัวอย่าง
<script src="https://apis.google.com/js/api.js"></script>
<script>
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/yt-analytics.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); });
}
function loadClient() {
return gapi.client.load("https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); });
}
// Make sure the client is loaded and sign-in is complete before calling this method.
function execute() {
return gapi.client.youtubeAnalytics.reports.query({
"ids": "channel==MINE",
"startDate": "2017-01-01",
"endDate": "2017-12-31",
"metrics": "views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage,subscribersGained",
"dimensions": "day",
"sort": "day"
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); });
}
gapi.load("client:auth2", function() {
gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});
});
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>
เนื้อหาของหน้าเว็บนี้ได้รับอนุญาตภายใต้ใบอนุญาตที่ต้องระบุที่มาของครีเอทีฟคอมมอนส์ 4.0 และตัวอย่างโค้ดได้รับอนุญาตภายใต้ใบอนุญาต Apache 2.0 เว้นแต่จะระบุไว้เป็นอย่างอื่น โปรดดูรายละเอียดที่นโยบายเว็บไซต์ Google Developers Java เป็นเครื่องหมายการค้าจดทะเบียนของ Oracle และ/หรือบริษัทในเครือ
อัปเดตล่าสุด 2025-08-21 UTC
[null,null,["อัปเดตล่าสุด 2025-08-21 UTC"],[[["\u003cp\u003eThis sample code uses the Google APIs Client Library for JavaScript to retrieve daily views and other metrics for a YouTube channel for the 2017 calendar year, utilizing the YouTube Analytics API.\u003c/p\u003e\n"],["\u003cp\u003eThe code requests user permission to access the \u003ccode\u003ehttps://www.googleapis.com/auth/yt-analytics.readonly\u003c/code\u003e scope to read YouTube Analytics data.\u003c/p\u003e\n"],["\u003cp\u003eSetting up authorization credentials in the Google API Console is required, including creating an OAuth client ID, enabling the YouTube Analytics API, and entering authorized JavaScript origins.\u003c/p\u003e\n"],["\u003cp\u003eThe sample requires replacing \u003ccode\u003e<var translate="no">YOUR_CLIENT_ID</var>\u003c/code\u003e with the client ID obtained from the Google API Console in order to run.\u003c/p\u003e\n"],["\u003cp\u003eTo run the code, users must authorize the application, load the API client, and execute the API query by clicking buttons in the browser, with successful operations and responses being logged in the browser's console.\u003c/p\u003e\n"]]],["The code uses the Google APIs Client Library for JavaScript to retrieve YouTube channel statistics. It requires user authorization for the `https://www.googleapis.com/auth/yt-analytics.readonly` scope. Users need to create authorization credentials in the Google API Console, enabling the YouTube Analytics API. The client ID must be added to the code sample, which is loaded from a specified URL. Upon running, the code allows authorization and data retrieval, displaying daily channel metrics (views, watch time, etc.) for 2017.\n"],null,["# JavaScript Code Samples\n\nThe code sample below uses the [Google APIs Client Library for JavaScript](/api-client-library/javascript). You can download this sample from the `javascript` folder of the [YouTube APIs code sample repository on GitHub](https://github.com/youtube/api-samples).\n\nThe code requests the user's permission to access the `https://www.googleapis.com/auth/yt-analytics.readonly` scope. \n\n```\nreturn gapi.auth2.getAuthInstance()\n .signIn({scope: \"https://www.googleapis.com/auth/yt-analytics.readonly\"})\n ...\n```\n\nYour application might also need to request access to other scopes. For example, an application that calls the YouTube Analytics API and the YouTube Data API might need users to also grant access to their YouTube accounts. The [authorization overview](/youtube/reporting/guides/authorization#identify-access-scopes) identifies scopes typically used in applications that call the YouTube Analytics API.\n\nRetrieve daily channel statistics\n---------------------------------\n\nThis example calls the YouTube Analytics API to retrieve daily views and other metrics for the authorizing user's channel for the 2017 calendar year. The sample uses the [Google APIs JavaScript client library](/api-client-library/javascript).\n\n### Set up authorization credentials\n\nBefore running this sample locally for the first time, you need to set up authorization credentials for your project:\n\n1. Create or select a project in the [Google API Console](https://console.cloud.google.com/).\n2. Enable the [YouTube Analytics API](https://console.developers.google.com/apis/library/youtubeanalytics.googleapis.com) for your project.\n3. At the top of the [Credentials](https://console.developers.google.com/apis/credentials) page, select the **OAuth consent screen** tab. Select an Email address, enter a Product name if not already set, and click the Save button.\n4. On the [Credentials](https://console.developers.google.com/apis/credentials) page, click the **Create credentials** button and select **Oauth client ID**.\n5. Select the application type Web application.\n6. In the Authorized JavaScript origins field, enter the URL from which you will be serving the code sample. For example, you could use something like `http://localhost:8000` or `http://yourserver.example.com`. You can leave the Authorized redirect URIs field blank.\n7. Click the **Create** button to finish creating your credentials.\n8. Before closing the dialog box, copy the client ID, which you will need to put into the code sample.\n\n### Make a local copy of the sample\n\nThen, save the sample to a local file. In the sample, find the following line and replace \u003cvar translate=\"no\"\u003eYOUR_CLIENT_ID\u003c/var\u003e with the client ID you obtained when setting up your authorization credentials. \n\n```\ngapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});\n```\n\n### Run the code\n\nNow, you are ready to actually test the sample:\n\n1. Open the local file from a web browser, and open the debugging console in the browser. You should see a page that displays two buttons.\n2. Click the **authorize and load** button to launch the user authorization flow. If you authorize the app to retrieve your channel data, you should see the following lines print to the console in the browser: \n\n ```\n Sign-in successful\n GAPI client loaded for API\n ```\n3. If you see an error message instead of the lines above, confirm that you are loading the script from the authorized redirect URI that you set up for your project and that you put your client ID into the code as described above.\n4. Click the **execute** button to call the API. You should see a `response` object print to the console in the browser. In that object, the `result` property maps to an object that contains the API data.\n\n### Sample code\n\n```javascript\n\u003cscript src=\"https://apis.google.com/js/api.js\"\u003e\u003c/script\u003e\n\u003cscript\u003e\n function authenticate() {\n return gapi.auth2.getAuthInstance()\n .signIn({scope: \"https://www.googleapis.com/auth/yt-analytics.readonly\"})\n .then(function() { console.log(\"Sign-in successful\"); },\n function(err) { console.error(\"Error signing in\", err); });\n }\n function loadClient() {\n return gapi.client.load(\"https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2\")\n .then(function() { console.log(\"GAPI client loaded for API\"); },\n function(err) { console.error(\"Error loading GAPI client for API\", err); });\n }\n // Make sure the client is loaded and sign-in is complete before calling this method.\n function execute() {\n return gapi.client.youtubeAnalytics.reports.query({\n \"ids\": \"channel==MINE\",\n \"startDate\": \"2017-01-01\",\n \"endDate\": \"2017-12-31\",\n \"metrics\": \"views,estimatedMinutesWatched,averageViewDuration,averageViewPercentage,subscribersGained\",\n \"dimensions\": \"day\",\n \"sort\": \"day\"\n })\n .then(function(response) {\n // Handle the results here (response.result has the parsed body).\n console.log(\"Response\", response);\n },\n function(err) { console.error(\"Execute error\", err); });\n }\n gapi.load(\"client:auth2\", function() {\n gapi.auth2.init({client_id: 'YOUR_CLIENT_ID'});\n });\n\u003c/script\u003e\n\u003cbutton onclick=\"authenticate().then(loadClient)\"\u003eauthorize and load\u003c/button\u003e\n\u003cbutton onclick=\"execute()\"\u003eexecute\u003c/button\u003e\nhttps://github.com/youtube/api-samples/blob/07263305b59a7c3275bc7e925f9ce6cabf774022/javascript/yt_analytics_v2.html\n```"]]