捆绑浏览器脚本 - AWS SDK for JavaScript

帮助我们改进AWS SDK for JavaScript版本 3 (V3) 文档,方法是使用反馈链接,或者在上创建议题或拉取请求GitHub.

这些区域有:AWS SDK for JavaScriptV3 API 参考指南详细描述了所有的 API 操作AWS SDK for JavaScript版本 3 (V3)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

捆绑浏览器脚本

本主题介绍如何捆绑浏览器脚本来捕获页面中的滚动进度并报告给 Kinesis 和所需的。AWS SDK for JavaScript此示例的模块。

如果您尚不了解,请按照先决条件任对于这个例子来安装 webpack。

注意

有关Webpack,请参阅使用 webpack 捆绑应用程序.

在命令行中运行以下命令,将此示例的 JavaScript 捆绑到名为的文件中<main.js>

webpack kinesis-example.js --mode development --target web --devtool false -o main.js

下面是 Kinesis 捕获网页滚动进度示例的完整浏览器脚本代码。

// Configure Credentials to use Cognito const { CognitoIdentityClient } = require("@aws-sdk/client-cognito-identity"); const { fromCognitoIdentityPool, } = require("@aws-sdk/credential-provider-cognito-identity"); const { Kinesis, PutRecordsCommand } = require("@aws-sdk/client-kinesis"); const REGION = "REGION"; const client = new Kinesis({ region: REGION, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({region: REGION}), identityPoolId: "IDENTITY_POOL_ID" // IDENTITY_POOL_ID }) }); // Get the ID of the web page element. var blogContent = document.getElementById('BlogContent'); // Get scrollable height. var scrollableHeight = blogContent.clientHeight; var recordData = []; var TID = null; blogContent.addEventListener('scroll', function(event) { console.log('scrolled'); clearTimeout(TID); // Prevent creating a record while a user is actively scrolling. TID = setTimeout(function() { // Calculate the percentage. var scrollableElement = event.target; var scrollHeight = scrollableElement.scrollHeight; var scrollTop = scrollableElement.scrollTop; var scrollTopPercentage = Math.round((scrollTop / scrollHeight) * 100); var scrollBottomPercentage = Math.round(((scrollTop + scrollableHeight) / scrollHeight) * 100); // Create the Amazon Kinesis record. var record = { Data: JSON.stringify({ blog: window.location.href, scrollTopPercentage: scrollTopPercentage, scrollBottomPercentage: scrollBottomPercentage, time: new Date() }), PartitionKey: 'PARTITION_KEY' // Must be a string. }; recordData.push(record); }, 100); }); // Helper function to upload data to Amazon Kinesis. const uploadData = async () => { try { const data = await client.send(new PutRecordsCommand({ Records: recordData, StreamName: 'STREAM_NAME' })); console.log('data', data); console.log("Kinesis updated", data); } catch (err) { console.log("Error", err); } }; // Run uploadData every second if data exists. setInterval(function() { if (!recordData.length) { return; } uploadData(); // clear record data recordData = []; }, 1000);