如何在不需要用户登录的情况下在网站上使用来自 Google Sheet 的数据?
How can I use data from a Google Sheet on a website without needing the user to be logged in?
我正在尝试使用 Google 表格作为动态 Web 应用程序的数据源,而不需要用户在客户端登录。我正在使用来自 this post 的 Bang 的回答,但我自己仍然需要登录 Google 才能访问要提供的电子表格。我做错了什么还是这仍然是预期的行为?有没有其他方法可以使网站应用程序无需用户登录即可访问电子表格?我创建了一个 'service user' 以尝试实现此目的但不确定是否正确(另外我似乎无法弄清楚如何将服务用户身份验证合并到下面的代码中。任何帮助都是非常感谢,谢谢。
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = 'xxxxxx';
var API_KEY = 'xxxxxx';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/spreadsheets.readonly";
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
listData();
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* @param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print data from spreadsheet
* https://docs.google.com/spreadsheets/d/xxxxxx/edit
*/
function listData() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: 'xxxxxx',
range: 'Sheet2!B2:E'
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
appendPre('Account Name, Account ID, Rent:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
if (row[1] == 'xxxxxx') {
console.log(row[0]);
appendPre(row[0] + ', ' + row[1] + ', ' + row[2]);
}
}
} else {
appendPre('No data found.');
}
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
那么,您的主要目标是 Use data from a Google Sheet on a website without needing the user to be logged in
。
解决这个问题的一个简单方法是在 Apps 脚本中部署一个 Web 应用程序,作为一种 REST API。
步骤如下:
- 创建一个从电子表格收集数据的函数。我正在使用 this Google 表格作为模拟数据。
RestAPI.gs
const collectData = () => {
const ss_id = SPREADSHEET_ID
const ss = SpreadsheetApp.openById(ss_id).getSheetByName('Class Data')
const rangeData = ss.getRange('A2:F31').getValues()
return rangeData
}
- 部署一个 Web 应用程序,作为
JSON
提供该数据。我把参数Who has access
设置为Anyone
(复制保存部署URL)
RestAPI.gs
const doGet = () => {
const response = ContentService.createTextOutput()
response.setContent(JSON.stringify({"data":collectData()}))
response.setMimeType(ContentService.MimeType.JSON)
return response
}
- 在您的应用程序中使用此“REST API”。就我而言,我将为此目的创建一个新的 Google Apps 脚本。
Web.gs
const doGet = () => HtmlService.createTemplateFromFile('index').evaluate()
const URL_TO_FETCH = URL_REST_API
const fetchData = () => UrlFetchApp.fetch(URL_TO_FETCH).getContentText()
index.html
<h1>RESULT</h1>
<div id="result"></div>
<script>
const onSuccess = data => {
const result = document.getElementById('result')
const userArr = JSON.parse(data).data
userArr.forEach(user=>{
result.innerHTML += `<div>${user.join(" ")}</div>`
})
}
google.script.run
.withSuccessHandler(onSuccess)
.fetchData()
</script>
通过这种方式,您可以使用一种方法来公开 Google 工作表的信息,而无需实施日志系统。
当然,此信息是公开的,任何有权访问您的 REST API link 的人都可以访问它。实施 OAuth 系统总是会更安全。
文档:
我正在尝试使用 Google 表格作为动态 Web 应用程序的数据源,而不需要用户在客户端登录。我正在使用来自 this post 的 Bang 的回答,但我自己仍然需要登录 Google 才能访问要提供的电子表格。我做错了什么还是这仍然是预期的行为?有没有其他方法可以使网站应用程序无需用户登录即可访问电子表格?我创建了一个 'service user' 以尝试实现此目的但不确定是否正确(另外我似乎无法弄清楚如何将服务用户身份验证合并到下面的代码中。任何帮助都是非常感谢,谢谢。
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = 'xxxxxx';
var API_KEY = 'xxxxxx';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/spreadsheets.readonly";
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
listData();
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* @param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print data from spreadsheet
* https://docs.google.com/spreadsheets/d/xxxxxx/edit
*/
function listData() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: 'xxxxxx',
range: 'Sheet2!B2:E'
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
appendPre('Account Name, Account ID, Rent:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
if (row[1] == 'xxxxxx') {
console.log(row[0]);
appendPre(row[0] + ', ' + row[1] + ', ' + row[2]);
}
}
} else {
appendPre('No data found.');
}
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
那么,您的主要目标是 Use data from a Google Sheet on a website without needing the user to be logged in
。
解决这个问题的一个简单方法是在 Apps 脚本中部署一个 Web 应用程序,作为一种 REST API。
步骤如下:
- 创建一个从电子表格收集数据的函数。我正在使用 this Google 表格作为模拟数据。
RestAPI.gs
const collectData = () => {
const ss_id = SPREADSHEET_ID
const ss = SpreadsheetApp.openById(ss_id).getSheetByName('Class Data')
const rangeData = ss.getRange('A2:F31').getValues()
return rangeData
}
- 部署一个 Web 应用程序,作为
JSON
提供该数据。我把参数Who has access
设置为Anyone
(复制保存部署URL)
RestAPI.gs
const doGet = () => {
const response = ContentService.createTextOutput()
response.setContent(JSON.stringify({"data":collectData()}))
response.setMimeType(ContentService.MimeType.JSON)
return response
}
- 在您的应用程序中使用此“REST API”。就我而言,我将为此目的创建一个新的 Google Apps 脚本。
Web.gs
const doGet = () => HtmlService.createTemplateFromFile('index').evaluate()
const URL_TO_FETCH = URL_REST_API
const fetchData = () => UrlFetchApp.fetch(URL_TO_FETCH).getContentText()
index.html
<h1>RESULT</h1>
<div id="result"></div>
<script>
const onSuccess = data => {
const result = document.getElementById('result')
const userArr = JSON.parse(data).data
userArr.forEach(user=>{
result.innerHTML += `<div>${user.join(" ")}</div>`
})
}
google.script.run
.withSuccessHandler(onSuccess)
.fetchData()
</script>
通过这种方式,您可以使用一种方法来公开 Google 工作表的信息,而无需实施日志系统。
当然,此信息是公开的,任何有权访问您的 REST API link 的人都可以访问它。实施 OAuth 系统总是会更安全。