Google Apps Script跨脚本调用含dataframe-js的库时出现参数类型错误问题
This issue stems from context isolation in Google Apps Script (GAS) libraries and how dataframe-js handles type validation. Let’s break down what’s happening:
Root Cause
When you set up script1 as a library for script2, the two scripts run in separate execution contexts. This creates a critical mismatch:
- The
Arrayconstructor in script1’s library context is not the same as theArrayconstructor in script2’s main context. - dataframe-js relies on type checks like
instanceof Arrayor custom validation that expects objects to originate from the same context as the library code.
When you pass your array [[1,2,3],['a','b','c']] from script2 to the library’s DataFrame constructor, the library’s type checker doesn’t recognize it as a valid Array. It sees the array as an instance of script2’s Array (not script1’s), so it throws the confusing error ArgumentTypeError: Array while expecting DataFrame | Array | Object.
When you paste dataframe-js directly into script2, everything works because the array and library code share the same execution context—type checks pass as intended.
Workaround Solutions
Here are a few ways to fix this:
Rehydrate data in the library’s context
Serialize and deserialize your data using the library’sJSONmethods to create an array that belongs to the library’s context:function test(){ var data = [[1,2,3],['a','b','c']] // Convert data to a library-compatible array var libraryData = script1.JSON.parse(script1.JSON.stringify(data)); var DataFrame = script1.dfjs.DataFrame var df = new DataFrame(libraryData) }The parsed array is created within the library’s context, so
instanceof Arraychecks will return true for dataframe-js’s validation.Adjust dataframe-js’s type checking logic
If you can modify the dataframe-js code in script1, replace context-dependent checks (likevalue instanceof Array) with context-agnostic alternatives:- Use
Array.isArray(value)(works across contexts) - Or use
Object.prototype.toString.call(value) === '[object Array]'for reliable type detection
Look for validation logic in the
_constructor_buildmethods referenced in your error stack and update those checks.- Use
Use inline code instead of a library
As you already found, pasting dataframe-js directly into each script that needs it avoids context mismatch entirely. This is the simplest fix if you don’t need to share the library across many projects.
Why This Happens in GAS
GAS libraries aren’t just code imports—they’re separate script projects running in isolated global scopes. This isolation prevents conflicts but also means native object constructors (like Array, Object) aren’t shared between the main script and library. Any type check relying on constructor identity (via instanceof) will fail when passing objects across this boundary.
内容的提问来源于stack exchange,提问作者jason

