Google Sheets HTML侧边栏数据获取报错及新工作表创建问题
Let's break down exactly what's going wrong here, and how to fix it:
Why You're Getting This Error
The document object is part of the browser's DOM API—it only exists in the client-side (your web browser running the sidebar HTML). Your Google Apps Script .gs files run on Google's servers, not in your browser, so they have no access to document at all. All those calls to document in your server-side script are the root cause of the error.
Step-by-Step Fix
1. Update Your Sidebar HTML to Handle Form Inputs Client-Side
First, modify your HTML sidebar to capture the form values using browser-side JavaScript, then send those values to your server-side script using google.script.run (the official way to communicate between client and server in GAS).
Here's a corrected version of your HTML:
<!DOCTYPE html> <html> <head> <base target="_top"> </head> <body> <form id="myForm"> <label for="assessmentName">Assessment Name:</label> <input type="text" id="assessmentName" name="assessmentName"><br><br> <!-- Add other form fields here if needed --> <button type="button" onclick="submitForm()">Create Sheet</button> </form> <script> function submitForm() { // Get form values from the DOM (safe here, since we're in the browser) const assessmentName = document.getElementById('assessmentName').value; // Note: Fixed the spelling of getElementById (capital B and I—case-sensitive!) // Send the value to your server-side function google.script.run .withSuccessHandler(() => { alert('Sheet created successfully!'); document.getElementById('myForm').reset(); // Reset form after success }) .withFailureHandler(error => { alert('Error creating sheet: ' + error.message); }) .createNewSheet(assessmentName); // Calls your .gs function } </script> </body> </html>
2. Clean Up Your Server-Side .gs Script
Remove all references to document from your server-side code—its only job now is to receive the value from the client and create the sheet:
function showSidebar() { const html = HtmlService.createHtmlOutputFromFile('Sidebar') .setTitle('Create New Assessment Sheet'); SpreadsheetApp.getUi().showSidebar(html); } function createNewSheet(assessmentName) { if (!assessmentName) { throw new Error('Please enter an assessment name'); } const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Create the new sheet with the provided name activeSpreadsheet.insertSheet(assessmentName); }
Key Fixes Recap
- Moved DOM access to client-side JS: All
documentcalls are now in the HTML's<script>tag, where they belong. - Fixed
getElementByIdspelling: You hadgetElementbyId(lowercase b and i)—this method name is case-sensitive! - Used
google.script.runfor client-server communication: This is the standard, secure way to pass data from your sidebar to your server-side script. - Server-side script focuses on spreadsheet logic: No more trying to access browser APIs where they don't exist.
内容的提问来源于stack exchange,提问作者Chris Shortreed

