I need help with getting a redirect URL from Google Sheets using Apps Script. I have two fitness forms - “Training Form X” and “Training Form Y”. Form X should automatically redirect to Form Y after submission but it’s not working properly.
I created a script that builds a URL and puts it in the last cell of my sheet. I want to grab that URL dynamically and use it for redirecting from Form X, but I keep getting errors.
URL Generation Script:
function onFormSubmit(e) {
createPrefilledURLs();
}
function createPrefilledURLs() {
const worksheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const allData = worksheet.getDataRange().getValues();
const headerRow = allData[0];
const dateColumn = headerRow.indexOf("Exercise Date");
const categoryColumn = headerRow.indexOf("Exercise Category");
if (dateColumn === -1 || categoryColumn === -1) {
throw new Error("Required headers 'Exercise Date' and/or 'Exercise Category' missing.");
}
const formURL = "https://docs.google.com/forms/d/e/1FAIpQLScojqj2IUfZSpyOATMsJKuTbr_iSGJ3NginEBY4wCwWddp8-A/viewform";
const urlColumn = headerRow.length + 1;
worksheet.getRange(1, urlColumn).setValue("Generated Form Link");
const finalRow = allData.length - 1;
const exerciseDate = encodeURIComponent(allData[finalRow][dateColumn]);
const exerciseCategory = encodeURIComponent(allData[finalRow][categoryColumn]);
const finalURL = `${formURL}?entry.9876543210=${exerciseDate}&entry.1357924680=${exerciseCategory}`;
worksheet.getRange(finalRow + 1, urlColumn).setValue(finalURL);
}
When I submit Form X, it creates the URL in the bottom right cell. I want to use that URL to update Form X’s redirect settings so it automatically fills Form Y.
Redirect Retrieval Script:
function doGet() {
const worksheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const sheetData = worksheet.getDataRange().getValues();
if (sheetData.length < 2) {
return HtmlService.createHtmlOutput("No data available.");
}
const bottomRow = sheetData.length - 1;
const rightmostCol = sheetData[0].length - 1;
const targetURL = sheetData[bottomRow][rightmostCol].toString().trim();
Logger.log("Retrieved URL: " + targetURL);
const redirectHTML = `
<html>
<head>
<meta http-equiv="refresh" content="0; url=${targetURL}" />
</head>
<body>
<p>Loading exercise form...</p>
</body>
</html>
`;
return HtmlService.createHtmlOutput(redirectHTML);
}
I deployed the script with “anyone with link” access and set execution as “me”. The URL generates correctly but I get a blank screen when trying to redirect. Previously I was getting invalid value errors. Any ideas what might be wrong?