Skip to content

Commit

Permalink
feat(printer): add createNewPage function
Browse files Browse the repository at this point in the history
  • Loading branch information
condorheroblog committed Apr 28, 2023
1 parent be517a3 commit cf0d48d
Showing 1 changed file with 48 additions and 36 deletions.
84 changes: 48 additions & 36 deletions src/core/printer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,48 +105,60 @@ export class Printer extends EventEmitter {
return this.browser;
}

async createNewPage(input: string) {
if (!this.browser)
await this.setup();
const page = await this.browser!.newPage();
this.pages.set(input, page);
page.setDefaultTimeout(this.timeout);
await page.emulateMediaType(this.emulateMedia);

if (this.needsAllowedRules()) {
await page.setRequestInterception(true);

page.on("request", (request) => {
const uri = new URL(request.url());
const { host, protocol, pathname } = uri;
const local = protocol === "file:";

if (local && !this.withinAllowedPath(pathname)) {
request.abort();
return;
}

if (local && !this.allowLocal) {
request.abort();
return;
}

if (host && !this.isAllowedDomain(host)) {
request.abort();
return;
}

if (host && !this.allowRemote) {
request.abort();
return;
}

request.continue();
});
}
return page;
}

async render(input: string) {
if (!this.browser)
await this.setup();

try {
const page = await this.browser!.newPage();
this.pages.set(input, page);
page.setDefaultTimeout(this.timeout);
await page.emulateMediaType(this.emulateMedia);

if (this.needsAllowedRules()) {
await page.setRequestInterception(true);

page.on("request", (request) => {
const uri = new URL(request.url());
const { host, protocol, pathname } = uri;
const local = protocol === "file:";

if (local && !this.withinAllowedPath(pathname)) {
request.abort();
return;
}

if (local && !this.allowLocal) {
request.abort();
return;
}

if (host && !this.isAllowedDomain(host)) {
request.abort();
return;
}

if (host && !this.allowRemote) {
request.abort();
return;
}

request.continue();
});
let page = this.pages.get(input);
if (!page) {
page = await this.createNewPage(input)
.catch((e) => {
throw e;
});
}

await page.goto(input, { waitUntil: "networkidle2" });
this.content = await page.content();

Expand Down

0 comments on commit cf0d48d

Please sign in to comment.