73 lines
2.2 KiB
JavaScript
73 lines
2.2 KiB
JavaScript
/**
|
|
* Google Apps Script to handle POST requests from the Chrome Extension
|
|
* 1. Create a new Google Sheet.
|
|
* 2. Extensions > Apps Script.
|
|
* 3. Paste this code.
|
|
* 4. Deploy > New Deployment > Web App.
|
|
* 5. Set 'Execute as: Me' and 'Who has access: Anyone'.
|
|
* 6. Copy the Web App URL and paste it into the Extension.
|
|
*/
|
|
|
|
function doPost(e) {
|
|
try {
|
|
var data = JSON.parse(e.postData.contents);
|
|
var ss = SpreadsheetApp.getActiveSpreadsheet();
|
|
var sheet;
|
|
|
|
// 1. Get or Create the target sheet
|
|
if (data.sheetName) {
|
|
sheet = ss.getSheetByName(data.sheetName);
|
|
if (!sheet) {
|
|
sheet = ss.insertSheet(data.sheetName);
|
|
}
|
|
} else {
|
|
sheet = ss.getActiveSheet();
|
|
}
|
|
|
|
var headers = [];
|
|
|
|
// 2. Determine headers
|
|
if (sheet.getLastRow() === 0) {
|
|
// Use provided headers if available
|
|
if (data.headers && Array.isArray(data.headers)) {
|
|
headers = data.headers;
|
|
} else {
|
|
// Fallback: Use keys but exclude internal control keys
|
|
headers = Object.keys(data).filter(function(key) {
|
|
return !["sheetName", "headers"].includes(key);
|
|
});
|
|
}
|
|
sheet.appendRow(headers);
|
|
} else {
|
|
// Get existing headers from the first row
|
|
var lastCol = sheet.getLastColumn();
|
|
if (lastCol > 0) {
|
|
headers = sheet.getRange(1, 1, 1, lastCol).getValues()[0];
|
|
}
|
|
}
|
|
|
|
// 3. Map data to headers
|
|
var row = headers.map(function(header) {
|
|
var val = data[header];
|
|
if (val === undefined || val === null) return "N/A";
|
|
// If value is an object or array, stringify it to avoid [Ljava.lang.Object]
|
|
if (typeof val === 'object') return JSON.stringify(val);
|
|
return val;
|
|
});
|
|
|
|
sheet.appendRow(row);
|
|
|
|
return ContentService.createTextOutput(JSON.stringify({ status: "success", sheet: sheet.getName() }))
|
|
.setMimeType(ContentService.MimeType.JSON);
|
|
|
|
} catch (error) {
|
|
return ContentService.createTextOutput(JSON.stringify({ status: "error", message: error.toString() }))
|
|
.setMimeType(ContentService.MimeType.JSON);
|
|
}
|
|
}
|
|
|
|
function doOptions(e) {
|
|
return ContentService.createTextOutput("")
|
|
.setMimeType(ContentService.MimeType.TEXT);
|
|
}
|