如何将木偶芯与电子一起使用? [英] How to use puppeteer-core with electron?

查看:117
本文介绍了如何将木偶芯与电子一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从另一个Stackoverflow问题中得到了这段代码:

 从电子中导入电子; 
从 puppeteer-core导入puppeteer;

const delay =(ms:number)=>
新的Promise(resolve => {
setTimeout(()=> {
resolve();
},ms);
});

(async()=> {
try {
const app =等待puppeteer.launch({
可执行文件路径:电子,
参数:[ 。],
headless:false,
});
const pages =等待app.pages();
const [page] = pages;

await page.setViewport({width:1200,height:700});
await delay(5000);
const image = await page.screenshot();
console.log (图片);
等待page.close();
等待延迟(2000);
等待app.close();
} catch(error){
console.error(error);
}
})();

Typescript编译器抱怨 executablePath 属性启动方法选项对象,因为它需要的类型为 string ,而不是 Electron 。那么如何将电子铬可执行文件的路径传递给puppeteer? 。他们在API方面有很多差异。特别是电子不具有所有的 chrome。* API,这是铬浏览器正常工作所必需的,许多标志仍然没有适当的替代,例如无头标志



下面您将看到两种方法。但是,您需要确保两点。




  • 在启动应用程序之前,确保木偶已连接。

  • 确保为在Electron中运行的Chrome版本获得正确的puppeteer或puppeteer-core版本!



使用电子伪造者



有很多解决方法,但是最近有电子木偶软件包,该软件包可让您使用电子在电子应用程序中运行木偶。



首先,安装依赖项,

  npm install puppeteer-in -电子木偶核心电子

然后运行它。

 从 electron导入{BrowserWindow,app}; 
的进口馅饼,来自电子偶;
从 puppeteer-core导入puppeteer;

const main = async()=> {
const浏览器=等待pie.connect(app,puppeteer);

const window = new BrowserWindow();
const url = https://example.com/;
等待window.loadURL(url);

常量页面=等待pie.getPage(浏览器,窗口);
console.log(page.url());
window.destroy();
};

main();



获取调试端口并连接到它



另一种方法是获取电子应用程序的远程调试端口并连接到它。此解决方案由 trusktr共享在电子论坛上

  import {app,BrowserWindow,...}从电子 
从'node-fetch'

import *作为puppeteer从'puppeteer'

app * commandLine.appendSwitch('remote-debugging-port','8315')

异步函数test(){
const response = await fetch(`http:// localhost:8315 / json / versions / list?t = $ {Math.random()}` )
const debugEndpoints =等待response.json()

let webSocketDebuggerUrl = debugEndpoints ['webSocketDebuggerUrl']

const browser = await puppeteer.connect({
browserWSEndpoint:webSocketDebuggerUrl
})

//立即使用伪造的API!
}

// ...像平常一样打开窗口,然后:...

//等待窗口打开/加载,然后将Puppeteer连接到它:
mainWindow.webContents.on( did-finish-load,()=> {
test()
})

以上两种解决方案均使用 webSocketDebuggerUrl 解决此问题。



额外



添加此注释是因为大多数人使用电子束缚应用程序。



如果要构建p核心和电子p,则需要使用危险电子生成器以确保 get-port-cli 起作用。



添加危险在main.js之上

  // main.js 
需要(危险);

确保已解压缩get-port-cli脚本,在package.json上添加以下内容

  build:{
asarUnpack: node_modules / get-port-cli
}

构建后的结果:




I got this code from another Stackoverflow Question:

import electron from "electron";
import puppeteer from "puppeteer-core";

const delay = (ms: number) =>
  new Promise(resolve => {
    setTimeout(() => {
      resolve();
    }, ms);
  });

(async () => {
  try {
    const app = await puppeteer.launch({
      executablePath: electron,
      args: ["."],
      headless: false,
    });
    const pages = await app.pages();
    const [page] = pages;

    await page.setViewport({ width: 1200, height: 700 });
    await delay(5000);
    const image = await page.screenshot();
    console.log(image);
    await page.close();
    await delay(2000);
    await app.close();
  } catch (error) {
    console.error(error);
  }
})();

Typescript compiler complains about executablePath property of launch method options object cause it needs to be of type string and not Electron. So how to pass electron chromium executable path to puppeteer?

解决方案

You cannot use electron executable with Puppeteer directly without some workarounds and flag changes. They have tons of differences in the API. Specially electron doesn't have all of the chrome.* API which is needed for chromium browser to work properly, many flags still doesn't have proper replacements such as the headless flag.

Below you will see two ways to do it. However you need to make sure of two points,

  • Make sure the puppeteer is connected before the app is initiated.
  • Make sure you get the correct version puppeteer or puppeteer-core for the version of Chrome that is running in Electron!

Use puppeteer-in-electron

There are lots of workarounds, but most recently there is a puppeteer-in-electron package which allows you to run puppeteer within electron app using the electron.

First, install the dependencies,

npm install puppeteer-in-electron puppeteer-core electron

Then run it.

import {BrowserWindow, app} from "electron";
import pie from "puppeteer-in-electron";
import puppeteer from "puppeteer-core";

const main = async () => {
  const browser = await pie.connect(app, puppeteer);

  const window = new BrowserWindow();
  const url = "https://example.com/";
  await window.loadURL(url);

  const page = await pie.getPage(browser, window);
  console.log(page.url());
  window.destroy();
};

main();

Get the debugging port and connect to it

The another way is to get the remote-debugging-port of the electron app and connect to it. This solution is shared by trusktr on electron forum.

import {app, BrowserWindow, ...} from "electron"
import fetch from 'node-fetch'

import * as puppeteer from 'puppeteer'

app.commandLine.appendSwitch('remote-debugging-port', '8315')

async function test() {
    const response = await fetch(`http://localhost:8315/json/versions/list?t=${Math.random()}`)
    const debugEndpoints = await response.json()

    let webSocketDebuggerUrl = debugEndpoints['webSocketDebuggerUrl ']

    const browser = await puppeteer.connect({
        browserWSEndpoint: webSocketDebuggerUrl
    })

    // use puppeteer APIs now!
}

// ... make your window, etc, the usual, and then: ...

  // wait for the window to open/load, then connect Puppeteer to it:
  mainWindow.webContents.on("did-finish-load", () => { 
    test()
  })

Both solution above uses webSocketDebuggerUrl to resolve the issue.

Extra

Adding this note because most people uses electron to bundle the app.

If you want to build the puppeteer-core and puppeteer-in-electron, you need to use hazardous and electron-builder to make sure get-port-cli works.

Add hazardous on top of main.js

// main.js
require ('hazardous');

Make sure the get-port-cli script is unpacked, add the following on package.json

"build": {
  "asarUnpack": "node_modules/get-port-cli"
}

Result after building:

这篇关于如何将木偶芯与电子一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆