Files
item-scraper/google-script.js
2026-03-11 12:58:38 -04:00

60 lines
1.7 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();
}
// 2. Get headers
var lastCol = sheet.getLastColumn();
var headers = [];
if (lastCol > 0) {
headers = sheet.getRange(1, 1, 1, lastCol).getValues()[0];
}
// 3. If sheet is empty, set headers from JSON keys
if (headers.length === 0 || headers[0] === "") {
headers = Object.keys(data);
sheet.appendRow(headers);
}
// 4. Map data to headers
var row = headers.map(function(header) {
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);
}