15 lines
2.8 KiB
JavaScript
15 lines
2.8 KiB
JavaScript
import {spawn} from 'node:child_process';
|
|
import {mkdtemp,rm} from 'node:fs/promises';
|
|
import os from 'node:os';import path from 'node:path';
|
|
export class Chrome {
|
|
async start(c,env={}){this.closed=false;this.dir=await mkdtemp(path.join(os.tmpdir(),'mars-chrome-'));if(this.closed){await rm(this.dir,{recursive:true,force:true});throw Error('Sitzung geschlossen');}this.pending=new Map();this.seq=0;this.buf=Buffer.alloc(0);this.closed=false;
|
|
this.proc=spawn('/usr/bin/'+c.engine,['--headless','--remote-debugging-pipe','--user-data-dir='+this.dir,'--no-first-run','--no-default-browser-check','--disable-background-networking','--autoplay-policy=no-user-gesture-required','--window-size='+c.width+','+c.height,'about:blank'],{stdio:['ignore','ignore','ignore','pipe','pipe'],env:{...process.env,...env}});
|
|
this.proc.on('error',e=>this.fail(e));this.proc.on('exit',()=>this.fail(Error('Chrome beendet')));this.proc.stdio[3].on('error',e=>this.fail(e));this.proc.stdio[4].on('error',e=>this.fail(e));this.proc.stdio[4].on('data',b=>{try{this.buf=Buffer.concat([this.buf,b]);if(this.buf.length>32*1024*1024)throw Error('CDP buffer');let i;while((i=this.buf.indexOf(0))>=0){const m=JSON.parse(this.buf.subarray(0,i).toString());this.buf=this.buf.subarray(i+1);const p=this.pending.get(m.id);if(p){clearTimeout(p.timer);this.pending.delete(m.id);m.error?p.reject(Error(m.error.message)):p.resolve(m.result);}else this.event?.(m);}}catch(e){this.fail(e);}});
|
|
const {targetInfos}=await this.call('Target.getTargets',{},null);const target=targetInfos.find(t=>t.type==='page')||await this.call('Target.createTarget',{url:'about:blank'},null);this.session=(await this.call('Target.attachToTarget',{targetId:target.targetId,flatten:true},null)).sessionId;await this.call('Page.enable');await this.resize(c.width,c.height);
|
|
}
|
|
call(method,params={},session=this.session){if(this.closed)return Promise.reject(Error('Chrome nicht verfügbar'));return new Promise((resolve,reject)=>{const id=++this.seq;const timer=setTimeout(()=>{this.pending.delete(id);reject(Error('CDP Timeout: '+method));},10000);this.pending.set(id,{resolve,reject,timer});this.proc.stdio[3].write(JSON.stringify({id,method,params,...(session?{sessionId:session}:{})})+'\0');});}
|
|
resize(width,height){return this.call('Emulation.setDeviceMetricsOverride',{width,height,deviceScaleFactor:1,mobile:false});}
|
|
fail(e){this.closed=true;for(const p of this.pending?.values()||[]){clearTimeout(p.timer);p.reject(e);}this.pending?.clear();}
|
|
async close(){this.fail(Error('Sitzung geschlossen'));if(this.proc&&this.proc.exitCode===null&&this.proc.signalCode===null){await new Promise(resolve=>{const t=setTimeout(()=>{this.proc.kill('SIGKILL');},1500);this.proc.once('close',()=>{clearTimeout(t);resolve();});this.proc.kill('SIGTERM');});}if(this.dir)await rm(this.dir,{recursive:true,force:true});}
|
|
}
|