简体   繁体   中英

Why I can't passing a variable into page url parameter in Puppeteer

I got an Error Error: Protocol error (Page.navigate): Invalid parameters Failed to deserialize params.url - BINDINGS: mandatory field missing at position 49...

When I passing a variable into page url parameter like this:

const puppeteer = require('puppeteer');

const BASE_URL = {
  production: 'https://foo.go.id',
  staging: 'https://foo.staging.com',
  development: 'http://localhost:3001',
}[process.env.NODE_ENV || 'staging'];

async function screenshotPage(bodyReq) {
  const { idElement, pageUrl, isGeneratePDF, token } = bodyReq;

  // Initialize puppeteer
  const browser = await puppeteer.launch({
    headless: true,
    args: ['--no-sandbox', '--disable-setuid-sandbox'],
  });

  const page = await browser.newPage();

  // Set breakpoint 1080p
  const override = Object.assign(page.viewport(), { width: 1920 });
  await page.setViewport(override);

  // No timeout when generating
  page.setDefaultNavigationTimeout(0);

  /**
   * Error when I passing a variable
   */
  await page.goto(BASE_URL, { waitUntil: 'load', timeout: 0 });
  const screenshot = await page.screenshot()

  return screenshot.toString('base64')
}

It's fine when passing the url without variable, but the problem is that different environment is different url :

const puppeteer = require('puppeteer');

const BASE_URL = {
  production: 'https://foo.go.id',
  staging: 'https://foo.staging.com',
  development: 'http://localhost:3001',
}[process.env.NODE_ENV || 'staging'];

async function screenshotPage(bodyReq) {
  const { idElement, pageUrl, isGeneratePDF, token } = bodyReq;

  // Initialize puppeteer
  const browser = await puppeteer.launch({
    headless: true,
    args: ['--no-sandbox', '--disable-setuid-sandbox'],
  });

  const page = await browser.newPage();

  // Set breakpoint 1080p
  const override = Object.assign(page.viewport(), { width: 1920 });
  await page.setViewport(override);

  // No timeout when generating
  page.setDefaultNavigationTimeout(0);

  /**
   * How can I know if the current environment is staging, production, or development
   * if I can't passing a variable
   */
  await page.goto('https://foo.staging.com', { waitUntil: 'load', timeout: 0 });
  const screenshot = await page.screenshot()

  return screenshot.toString('base64')
}

您是否尝试过使用字符串模板文字?

await page.goto(`${BASE_URL}`, { waitUntil: 'load', timeout: 0 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM