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

Electron集成Puppeteer时page.waitForSelector报错:Passed function is not well-serializable的解决方案求助

解决Electron中Puppeteer出现"Passed function is not well-serializable"错误的可行思路

这个错误本质是Electron的V8上下文和Puppeteer的页面上下文之间的序列化规则冲突导致的,尤其是当函数包含闭包引用、非可序列化对象,或者版本不匹配时容易触发。结合你的情况,给你几个优先级从高到低的解决方案:

1. 改用puppeteer-core并复用Electron自带的Chrome

普通puppeteer包会下载独立的Chrome,和Electron自带的Chrome版本可能不匹配,这是引发序列化问题的常见原因。换成puppeteer-core,直接使用Electron的可执行文件,能彻底避免版本兼容问题:

const puppeteer = require('puppeteer-core');
const { app } = require('electron');

async function scraper(url) {
  // 获取Electron自带的Chrome可执行文件路径
  const chromeExecutablePath = app.getPath('exe');
  
  const browser = await puppeteer.launch({
    executablePath: chromeExecutablePath,
    args: ['--no-sandbox', '--disable-setuid-sandbox'], // 解决Linux/macOS的权限限制
    headless: 'new', // 用新的无头模式,兼容性更好
    defaultViewport: null // 可选,根据需求设置视口
  });

  const page = await browser.newPage();
  await page.goto(url, { waitUntil: 'networkidle2' }); // 等待网络稳定,避免元素未加载
  const element = await page.waitForSelector('h1', { timeout: 5000 }); // 增加超时时间,防止误判
  console.log('element: ', element);

  await browser.close();
}

2. 避免在序列化函数中使用闭包引用

如果你后续用到page.evaluate()、page.waitForFunction()这类需要序列化函数的API,绝对不要直接引用外部变量(闭包),必须通过参数传递:

// 错误示例:闭包引用外部变量导致序列化失败
const myTitle = "Example Domain";
const isMatch = await page.evaluate(() => {
  return document.querySelector('h1').textContent === myTitle;
});

// 正确示例:通过参数传递外部变量
const isMatch = await page.evaluate((targetTitle) => {
  return document.querySelector('h1').textContent === targetTitle;
}, myTitle);

3. 临时禁用Electron的上下文隔离(谨慎使用)

如果上面的方法都无效,可以尝试关闭Electron的上下文隔离,但这会降低应用的安全性,仅建议在内部测试应用中使用:

在创建BrowserWindow时修改webPreferences:

const { BrowserWindow } = require('electron');

const mainWindow = new BrowserWindow({
  webPreferences: {
    contextIsolation: false,
    nodeIntegration: true
  }
});

4. 严格匹配Electron和Puppeteer的版本

不同版本的Electron对应不同版本的Chrome,而Puppeteer需要和Chrome版本匹配。你可以根据Electron的Chrome版本(在Electron官网查看对应版本的Chrome内核),选择对应版本的puppeteer-core。比如Electron 28对应Chrome 117,就选Puppeteer-core 21.x版本。


内容的提问来源于stack exchange,提问作者Patryk Karpiński

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:44:08