You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

同源策略限制下Groovy脚本过长触发js.exec字符上限问题求助

解决Geb中js.exec字符串过长的问题

这个问题我之前也碰到过,Geb的js.exec()确实有65535个Unicode单元的长度限制,你的脚本超了就会触发这个报错。这里有几个实用的解决办法:

方法1:拆分脚本为多个小片段执行

因为浏览器的JS上下文是持续的,你可以把长脚本拆分成几个独立的部分,分多次调用js.exec(),这样每个片段的长度都不会超过限制。

比如你可以先定义截图的函数,再加载外部脚本并调用这个函数:

and:'I define the capture function'
js.exec('''
function captureTopImage() {
  // 注意:这里你原来的width取的是height,应该是width(),避免截图变形
  var height = Math.round($("#TopImageContainer").height());
  var width = Math.round($("#TopImageContainer").width());
  
  html2canvas($("#TopImageContainer"), {
    onrendered: function (canvas) {
      var tempcanvas = document.createElement("canvas");
      tempcanvas.width = width;
      tempcanvas.height = height;
      var context = tempcanvas.getContext("2d");
      context.drawImage(canvas,0,0,width,height,0,0,width,height);
      var link = document.createElement("a");
      link.href = tempcanvas.toDataURL("image/png");
      link.download = "myElement.png";
      link.click();
    }
  });
}
''')

and:'I load the script and execute capture'
js.exec('''
$.getScript("http://localhost/jscript/html2canvas.js", function() {
  captureTopImage();
});
''')

这样拆分后,每个exec()传递的字符串长度都会远远低于限制,同时逻辑和原来完全一致。

方法2:将脚本内容存入本地文件,读取后分块执行(可选)

如果你的脚本后续还会扩展,也可以把完整的JS代码保存到本地文件(比如capture-image.js),然后在Groovy中读取文件内容,再拆分成合适的片段执行。不过这种方法比第一种稍复杂,适合脚本非常长的场景:

// 读取本地JS文件内容
def scriptContent = new File("path/to/capture-image.js").text
// 按一定长度拆分(比如每60000个字符为一段)
def chunks = scriptContent.split(/(?<=.{60000})/)
chunks.each { chunk ->
  js.exec(chunk)
}

不过第一种方法更简洁,也更容易维护,优先推荐。

另外提个小细节:你原来的代码里width变量取的是$("#TopImageContainer").height(),这应该是笔误,改成width()才能保证截图的宽高正确哦。

内容的提问来源于stack exchange,提问作者user4237435

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:49:50