英文:
Don't add data if its already in google sheet
问题
Sure, here's the translated code portion:
JavaScript部分:
if (performance.navigation.type != performance.navigation.TYPE_RELOAD) {
const queryParameters = Object.fromEntries(new URLSearchParams(window.location.search));
const scriptURL = 'https://script.google.com/macros/s/script/exec';
const data = new FormData();
Object.entries(queryParameters).forEach(e => data.append(...e));
fetch(scriptURL, { method: 'POST', body: data })
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
}
Google Script部分:
var sheetName = 'Sheet1';
var scriptProp = PropertiesService.getScriptProperties();
function intialSetup () {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
scriptProp.setProperty('key', activeSpreadsheet.getId());
}
function doPost (e) {
const { Name, Email, sample } = e.parameter;
if (sample == "delete") {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var ranges = sheet.getDataRange();
var values = ranges.getValues().filter(r => ![Name, Email].every(e => r.includes(e)));
if (values.length == 0) {
return ContentService.createTextOutput(`"${email}" was not found.`);
}
ranges.clearContent().offset(0, 0, values.length, values[0].length).setValues(values);
return ContentService.createTextOutput(`Rows including "${Email}" were deleted.`);
}
var lock = LockService.getScriptLock();
lock.tryLock(10000);
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'));
var sheet = doc.getSheetByName(sheetName);
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow() + 1;
var newRow = headers.map(function(header) {
return header === 'Timestamp' ? new Date() : e.parameter[header];
});
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow]);
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
.setMimeType(ContentService.MimeType.JSON);
} catch (e) {
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
.setMimeType(ContentService.MimeType.JSON);
} finally {
lock.releaseLock();
}
}
请注意,我已经根据您提供的代码进行了翻译,不包括问题部分。如果需要进一步的帮助,请告诉我。
英文:
Currently I have parameters being added to my google sheet on page load.
The URL looks like https://example.com/page?Name=John&Email=john@gmail.com
I'm wondering how I can stop this data being added a second time if people visit this URL again.
I currently stop a resubmission on page reload, but this doesn't stop a user if the URL is placed in a new tab, or opened on another device.
Is there a way to check if the same parameters are already in the sheet, and stop it being added if it is.
Javascript:
if (performance.navigation.type != performance.navigation.TYPE_RELOAD) {
const queryParameters = Object.fromEntries(new URLSearchParams(window.location.search));
const scriptURL = 'https://script.google.com/macros/s/script/exec';
const data = new FormData();
Object.entries(queryParameters).forEach(e => data.append(...e));
fetch(scriptURL, { method: 'POST', body: data })
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message))
}
Google Script
var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()
function intialSetup () {
var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
scriptProp.setProperty('key', activeSpreadsheet.getId())
}
function doPost (e) {
const { Name, Email, sample } = e.parameter;
if (sample == "delete") {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
var ranges = sheet.getDataRange();
var values = ranges.getValues().filter(r => ![Name, Email].every(e => r.includes(e)));
if (ranges.length == 0) {
return ContentService.createTextOutput(`"${email}" was not found.`);
}
ranges.clearContent().offset(0, 0, values.length, values[0].length).setValues(values);
return ContentService.createTextOutput(`Rows including "${Email}" were deleted.`);
}
var lock = LockService.getScriptLock()
lock.tryLock(10000)
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
var nextRow = sheet.getLastRow() + 1
var newRow = headers.map(function(header) {
return header === 'Timestamp' ? new Date() : e.parameter[header]
})
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
.setMimeType(ContentService.MimeType.JSON)
}
catch (e) {
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
.setMimeType(ContentService.MimeType.JSON)
}
finally {
lock.releaseLock()
}
}
I hope that makes sense, I am happy to clarify.
Thank you.
答案1
得分: 1
从:
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
到:
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
var values = sheet.getDataRange().getValues().filter(r => [Name, Email].every(e => r.includes(e)));
if (values.length > 0) {
return ContentService.createTextOutput("Values were not appended.");
}
- 通过这个修改,当
Name
和Email
的值存在时,脚本会停止。
注意:
-
当您修改Google Apps Script的Web Apps时,请将部署修改为新版本。通过这样做,修改后的脚本将反映在Web Apps中。请注意这一点。
-
您可以在我的报告中查看详细信息"Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)"。
参考资料:
英文:
In your script, how about the following modification?
From:
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
To:
try {
var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
var sheet = doc.getSheetByName(sheetName)
var values = sheet.getDataRange().getValues().filter(r => [Name, Email].every(e => r.includes(e)));
if (values.length > 0) {
return ContentService.createTextOutput("Values were not appended.");
}
- By this modification, when the values of
Name
andEmail
are existing, the script is stopped.
Note:
-
When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
-
You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
References:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论