Files
item-scraper/google-script.js
2026-03-11 13:01:18 -04:00

71 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. If sheet is brand new (no rows), create headers first
if (sheet.getLastRow() === 0) {
// Extract keys from data, excluding 'sheetName' which is a control parameter
headers = Object.keys(data).filter(function(key) {
return key !== "sheetName";
});
sheet.appendRow(headers);
} else {
// 3. If sheet already exists, get existing headers from the first row
var lastCol = sheet.getLastColumn();
if (lastCol > 0) {
headers = sheet.getRange(1, 1, 1, lastCol).getValues()[0];
} else {
// Fallback for edge cases where lastRow > 0 but lastCol is 0
headers = Object.keys(data).filter(function(key) {
return key !== "sheetName";
});
sheet.appendRow(headers);
}
}
// 4. Map data to the determined headers
var row = headers.map(function(header) {
// data[header] might be undefined for some rows if schema changes
return data[header] !== undefined ? data[header] : "N/A";
});
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);
}