Skip to content

Commit

Permalink
remove unnecessary formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
vitorfigueiraacin committed Oct 16, 2023
1 parent e17464d commit 77a9d0a
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 94 deletions.
160 changes: 66 additions & 94 deletions bin/browser.cjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const fs = require("fs");
const URL = require("url").URL;
const URLParse = require("url").parse;
const fs = require('fs');
const URL = require('url').URL;
const URLParse = require('url').parse;

const [, , ...args] = process.argv;

Expand All @@ -10,7 +10,7 @@ const [, , ...args] = process.argv;
* - Or by providing a temporary file with the options JSON dump,
* the path to this file is then given as an argument with the flag -f
*/
const request = args[0].startsWith("-f ")
const request = args[0].startsWith('-f ')
? JSON.parse(fs.readFileSync(new URL(args[0].substring(3))))
: JSON.parse(args[0]);

Expand All @@ -35,20 +35,20 @@ const getOutput = async (request, page = null) => {

if (
![
"requestsList",
"consoleMessages",
"failedRequests",
"redirectHistory",
"pageErrors",
'requestsList',
'consoleMessages',
'failedRequests',
'redirectHistory',
'pageErrors',
].includes(request.action) &&
page
) {
if (request.action == "evaluate") {
if (request.action == 'evaluate') {
output.result = await page.evaluate(request.options.pageFunction);
} else {
output.result = (
await page[request.action](request.options)
).toString("base64");
).toString('base64');
}
}

Expand All @@ -64,44 +64,39 @@ const callChrome = async (pup) => {
let browser;
let page;
let remoteInstance;
const puppet = pup || require("puppeteer");
const puppet = pup || require('puppeteer');

try {
if (
request.options.remoteInstanceUrl ||
request.options.browserWSEndpoint
) {
if (request.options.remoteInstanceUrl || request.options.browserWSEndpoint ) {
// default options
let options = {
ignoreHTTPSErrors: request.options.ignoreHttpsErrors,
ignoreHTTPSErrors: request.options.ignoreHttpsErrors
};

// choose only one method to connect to the browser instance
if (request.options.remoteInstanceUrl) {
if ( request.options.remoteInstanceUrl ) {
options.browserURL = request.options.remoteInstanceUrl;
} else if (request.options.browserWSEndpoint) {
} else if ( request.options.browserWSEndpoint ) {
options.browserWSEndpoint = request.options.browserWSEndpoint;
}

try {
browser = await puppet.connect(options);

remoteInstance = true;
} catch (exception) {
/** does nothing. fallbacks to launching a chromium instance */
}
} catch (exception) { /** does nothing. fallbacks to launching a chromium instance */}
}

if (!browser) {
browser = await puppet.launch({
headless: request.options.newHeadless ? "new" : true,
headless: request.options.newHeadless ? 'new' : true,
ignoreHTTPSErrors: request.options.ignoreHttpsErrors,
executablePath: request.options.executablePath,
args: request.options.args || [],
pipe: request.options.pipe || false,
env: {
...(request.options.env || {}),
...process.env,
...process.env
},
});
}
Expand All @@ -115,17 +110,15 @@ const callChrome = async (pup) => {
await page.setRequestInterception(true);

const contentUrl = request.options.contentUrl;
const parsedContentUrl = contentUrl
? contentUrl.replace(/\/$/, "")
: undefined;
const parsedContentUrl = contentUrl ? contentUrl.replace(/\/$/, '') : undefined;
let pageContent;

if (contentUrl) {
pageContent = fs.readFileSync(request.url.replace("file://", ""));
pageContent = fs.readFileSync(request.url.replace('file://', ''));
request.url = contentUrl;
}

page.on("console", (message) =>
page.on('console', (message) =>
consoleMessages.push({
type: message.type(),
message: message.text(),
Expand All @@ -134,18 +127,15 @@ const callChrome = async (pup) => {
})
);

page.on("pageerror", (msg) => {
page.on('pageerror', (msg) => {
pageErrors.push({
name: msg.name || "unknown error",
name: msg.name || 'unknown error',
message: msg.message || msg.toString(),
});
});

page.on("response", function (response) {
if (
response.request().isNavigationRequest() &&
response.request().frame().parentFrame() === null
) {
page.on('response', function (response) {
if (response.request().isNavigationRequest() && response.request().frame().parentFrame() === null) {
redirectHistory.push({
url: response.request().url(),
status: response.status(),
Expand All @@ -164,15 +154,15 @@ const callChrome = async (pup) => {
});
});

page.on("request", (interceptedRequest) => {
page.on('request', (interceptedRequest) => {
var headers = interceptedRequest.headers();

requestsList.push({
url: interceptedRequest.url(),
});

if (request.options && request.options.disableImages) {
if (interceptedRequest.resourceType() === "image") {
if (interceptedRequest.resourceType() === 'image') {
interceptedRequest.abort();
return;
}
Expand All @@ -198,18 +188,12 @@ const callChrome = async (pup) => {
if (request.options && request.options.extraNavigationHTTPHeaders) {
// Do nothing in case of non-navigation requests.
if (interceptedRequest.isNavigationRequest()) {
headers = Object.assign(
{},
headers,
request.options.extraNavigationHTTPHeaders
);
headers = Object.assign({}, headers, request.options.extraNavigationHTTPHeaders);
}
}

if (pageContent) {
const interceptedUrl = interceptedRequest
.url()
.replace(/\/$/, "");
const interceptedUrl = interceptedRequest.url().replace(/\/$/, '');

// if content url matches the intercepted request url, will return the content fetched from the local file system
if (interceptedUrl === parsedContentUrl) {
Expand All @@ -224,15 +208,15 @@ const callChrome = async (pup) => {
if (request.postParams) {
const postParamsArray = request.postParams;
const queryString = Object.keys(postParamsArray)
.map((key) => `${key}=${postParamsArray[key]}`)
.join("&");
.map(key => `${key}=${postParamsArray[key]}`)
.join('&');
interceptedRequest.continue({
method: "POST",
method: 'POST',
postData: queryString,
headers: {
...interceptedRequest.headers(),
"Content-Type": "application/x-www-form-urlencoded",
},
'Content-Type': 'application/x-www-form-urlencoded',
}
});
return;
}
Expand All @@ -241,7 +225,7 @@ const callChrome = async (pup) => {
});

if (request.options && request.options.dismissDialogs) {
page.on("dialog", async (dialog) => {
page.on('dialog', async (dialog) => {
await dialog.dismiss();
});
}
Expand Down Expand Up @@ -283,9 +267,8 @@ const callChrome = async (pup) => {
const requestOptions = {};

if (request.options && request.options.networkIdleTimeout) {
requestOptions.waitUntil = "networkidle";
requestOptions.networkIdleTimeout =
request.options.networkIdleTimeout;
requestOptions.waitUntil = 'networkidle';
requestOptions.networkIdleTimeout = request.options.networkIdleTimeout;
} else if (request.options && request.options.waitUntil) {
requestOptions.waitUntil = request.options.waitUntil;
}
Expand All @@ -296,13 +279,13 @@ const callChrome = async (pup) => {
const status = response.status();

if (status >= 400 && status < 600) {
throw { type: "UnsuccessfulResponse", status };
throw {type: 'UnsuccessfulResponse', status};
}
}

if (request.options && request.options.disableImages) {
await page.evaluate(() => {
let images = document.getElementsByTagName("img");
let images = document.getElementsByTagName('img');
while (images.length > 0) {
images[0].parentNode.removeChild(images[0]);
}
Expand All @@ -313,17 +296,13 @@ const callChrome = async (pup) => {
for (let i = 0, len = request.options.types.length; i < len; i++) {
let typeOptions = request.options.types[i];
await page.type(typeOptions.selector, typeOptions.text, {
delay: typeOptions.delay,
'delay': typeOptions.delay,
});
}
}

if (request.options && request.options.selects) {
for (
let i = 0, len = request.options.selects.length;
i < len;
i++
) {
for (let i = 0, len = request.options.selects.length; i < len; i++) {
let selectOptions = request.options.selects[i];
await page.select(selectOptions.selector, selectOptions.value);
}
Expand All @@ -333,9 +312,9 @@ const callChrome = async (pup) => {
for (let i = 0, len = request.options.clicks.length; i < len; i++) {
let clickOptions = request.options.clicks[i];
await page.click(clickOptions.selector, {
button: clickOptions.button,
clickCount: clickOptions.clickCount,
delay: clickOptions.delay,
'button': clickOptions.button,
'clickCount': clickOptions.clickCount,
'delay': clickOptions.delay,
});
}
}
Expand All @@ -356,39 +335,36 @@ const callChrome = async (pup) => {
await page.evaluate((initialPageNumber) => {
window.pageStart = initialPageNumber;

const style = document.createElement("style");
style.type = "text/css";
style.innerHTML =
".empty-page { page-break-after: always; visibility: hidden; }";
document.getElementsByTagName("head")[0].appendChild(style);

const emptyPages = Array.from({ length: window.pageStart }).map(
() => {
const emptyPage = document.createElement("div");
emptyPage.className = "empty-page";
emptyPage.textContent = "empty";
return emptyPage;
}
);
const style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.empty-page { page-break-after: always; visibility: hidden; }';
document.getElementsByTagName('head')[0].appendChild(style);

const emptyPages = Array.from({ length: window.pageStart }).map(() => {
const emptyPage = document.createElement('div');
emptyPage.className = 'empty-page';
emptyPage.textContent = 'empty';
return emptyPage;
});
document.body.prepend(...emptyPages);
}, request.options.initialPageNumber);
}

if (request.options.selector) {
var element;
const index = request.options.selectorIndex || 0;
if (index) {
if(index){
element = await page.$$(request.options.selector);
if (!element.length || typeof element[index] === "undefined") {
if(!element.length || typeof element[index] === 'undefined'){
element = null;
} else {
}else{
element = element[index];
}
} else {
}else{
element = await page.$(request.options.selector);
}
if (element === null) {
throw { type: "ElementNotFound" };
throw {type: 'ElementNotFound'};
}

request.options.clip = await element.boundingBox();
Expand All @@ -397,13 +373,9 @@ const callChrome = async (pup) => {
if (request.options.function) {
let functionOptions = {
polling: request.options.functionPolling,
timeout:
request.options.functionTimeout || request.options.timeout,
timeout: request.options.functionTimeout || request.options.timeout
};
await page.waitForFunction(
request.options.function,
functionOptions
);
await page.waitForFunction(request.options.function, functionOptions);
}

console.log(await getOutput(request, page));
Expand All @@ -412,7 +384,7 @@ const callChrome = async (pup) => {
await page.close();
}

(await remoteInstance) ? browser.disconnect() : browser.close();
await remoteInstance ? browser.disconnect() : browser.close();
} catch (exception) {
if (browser) {
if (remoteInstance && page) {
Expand All @@ -424,7 +396,7 @@ const callChrome = async (pup) => {

const output = await getOutput(request);

if (exception.type === "UnsuccessfulResponse") {
if (exception.type === 'UnsuccessfulResponse') {
output.exception = exception.toString();
console.error(exception.status);
console.log(JSON.stringify(output));
Expand All @@ -436,7 +408,7 @@ const callChrome = async (pup) => {
console.error(exception);
console.log(JSON.stringify(output));

if (exception.type === "ElementNotFound") {
if (exception.type === 'ElementNotFound') {
process.exit(2);
}

Expand Down
1 change: 1 addition & 0 deletions src/Browsershot.php
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,7 @@ public function base64Screenshot(): string
public function screenshot(): string
{
if ($this->imageManipulations->isEmpty()) {

$command = $this->createScreenshotCommand();
$encodedImage = $this->callBrowser($command);

Expand Down

0 comments on commit 77a9d0a

Please sign in to comment.