The same code does not work in headless mode [playwright] - headless

"": "^1.23.0",
In headless=false, it works.
In headless=true, I cannot pass this line:
await this.page.dispatchEvent('button[role="tab"]:has-text("Hello")', 'click')
and the error is:
node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
^
page.dispatchEvent: Target crashed
=========================== logs ===========================
waiting for selector "button[role="tab"]:has-text("Hello")"
============================================================
at Scrapper4_save.main (file:///Users/yo/0HOME/0GARAGE/demo/src/e2e/0-ts-out/e2e/Scrapper4_save.js:20:25)
at async file:///Users/yo/0HOME/0GARAGE/demo/src/e2e/0-ts-out/e2e/index.js:34:13 {
name: 'Error'
}
Is it posible to have the exact same working code in headless or headed mode ?
Do you know how to fix this issue ?
Tks

Related

Failed to create session. unknown error: Chrome failed to start: was killed. (unknown error: DevToolsActivePort file doesn't exist)

I'm executing an automated test with Electron by using Selenium by using the following code:
const webdriver = require('selenium-webdriver');
var Application = require('spectron').Application;
var assert = require('assert');
const driver = new webdriver.Builder()
// The "9515" is the port opened by chrome driver.
.usingServer('http://localhost:9515')
.withCapabilities({
'goog:chromeOptions': {
// Here is the path to your Electron binary.
binary: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
},
})
.forBrowser('electron') // note: use .forBrowser('electron') for selenium-webdriver <= 3.6.0
.build();
describe('Application launch', function () {
var app;
jest.setTimeout(30000);
beforeEach(function () {
app = new Application({
path: 'node_modules/.bin/electron',
args: ['--headless', '--no-sandbox', '--disable-dev-shm-usage'],
});
return app.start();
});
afterEach(function () {
if (app && app.isRunning()) {
return app.stop();
}
});
it('click a button', function* () {
yield driver.sleep(5000);
});
});
But I'm obtaining the following error:
yarn run v1.22.19
warning package.json: License should be a valid SPDX license expression
warning ..\..\..\package.json: No license field
$ jest --NODE_ENV=test
FAIL src/__test__/App.spec.jsx (10.623 s)
Application launch
× click a button (6564 ms)
● Application launch › click a button
Failed to create session.
unknown error: Chrome failed to start: was killed.
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location C:\Users\vipul\appname\src\node_modules\spectron\lib\launcher.bat is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
at startWebDriverSession (src/node_modules/webdriver/build/utils.js:72:15)
at Function.newSession (src/node_modules/webdriver/build/index.js:58:45)
at Object.remote (src/node_modules/webdriverio/build/index.js:73:22)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 11.878 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I've tried to add even the args suggested by several answers in other stackoverflow questions like --headless or --no-sandbox but even those not worked.
Try this file
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--no-sandbox");
options.add_argument("--headless")
options.add_argument("--disable-setuid-sandbox")
options.add_argument("--remote-debugging-port=9222") # this
options.add_argument("--disable-extensions")
#options.add_argument("--headless")
options.add_argument("--disable-gpu")
options.add_argument("enable-automation")
options.add_argument("--disable-infos")
options.add_argument("--disable-dev-shm-usage")
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.google.com/")
element_text = driver.page_source
print(element_text)

playwright firefox.launchPersistentContext timeout

I want to open a context using playwright firefox based on an session dir, on my pc, it work perfectly, but on 3 diffrent remote desktop connection pc (vps windows server) there are an error. The browser is open after 30s it say the error :
browserType.launchPersistentContext: Timeout 30000ms exceeded.
=========================== logs ===========================
<launching> C:\Users\Administrator\AppData\Local\ms-playwright\firefox-1322\firefox\firefox.exe -no-remote -wait-for-browser -foreground -profile ./browser_data/thread-test -juggler-pipe about:blank
<launched> pid=924
[pid=924][out]
[pid=924][out] Juggler listening to the pipe
[pid=924][err] IPDL protocol Error: Received an invalid file descriptor
[pid=924][err] IPDL protocol Error: Received an invalid file descriptor
[pid=924][err] IPDL protocol Error: Received an invalid file descriptor
============================================================
at async C:\Users\Administrator\Desktop\gen\index.js:128:23 {
name: 'TimeoutError'
}
error image
The code that I use :
const {firefox} = require('playwright')
const context = await firefox.launchPersistentContext('./browser_data/thread-test', {headless:false,});
I think there is an error on connect browser to playwright step but I don't know how to fix...
Thank you for your help !
import { rm } from 'fs';
import { firefox } from 'playwright';
rm('/context/sessionstore-backups', () => {});
rm('/context/sessionCheckpoints.json', () => {});
rm('/context/sessionstore.jsonlz4', () => {});
context = await firefox.launchPersistentContext(
'/context',
{ headless: false }
);
page = context.pages()[0];
Acctually, we need to remove sessionstore-backups and sessionstore.jsonlz4 in the userDataDir folder

Attempting to using Selenium Grid to run test with Microsoft Edge, SessionNotCreatedError

I am currently attempting to setup Selenium Grid using javascript and selenium-webdriver. I have my hub and node setup and currently have run successful tests on Chrome and Firefox. However, I am running into some trouble setting up a test for Microsoft Edge. Just a test that pulls up Google and prints the title.
const { Builder } = require("selenium-webdriver");
const edge = require("selenium-webdriver/edge");
let opts = new edge.Options();
(async function helloSelenium() {
let driver = new Builder()
.usingServer("http://XX.XX.XX.XX:4444/wd/hub")
.forBrowser('edge')
.setEdgeOptions(opts)
.build();
try {
await driver.get('http://www.google.com')
.then(() => driver.getTitle())
.then(title => console.log(title))
}
finally {
await driver.quit();
}
})();
The error I'm getting shows up on the command prompt in the hub (nothing shows up in the node). Showing as follows:
(node:8956) UnhandledPromiseRejectionWarning: SessionNotCreatedError: Unable to create session from {
"desiredCapabilities": {
"browserName": "edge",
"se:CONFIG_UUID": null
},
"capabilities": {
"firstMatch": [
{
"browserName": "edge"
}
]
}
}
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'MDEV', ip: 'XX.XX.XX.XX', os.name: '....', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_291'
Driver info: driver.version: unknown
at Object.checkLegacyResponse (C:\Users\Administrator\Documents\sel-testing\node_modules\selenium-webdriver\lib\error.js:553:15)
at parseHttpResponse (C:\Users\Administrator\Documents\sel-testing\node_modules\selenium-webdriver\lib\http.js:634:13)
at Executor.execute (C:\Users\Administrator\Documents\sel-testing\node_modules\selenium-webdriver\lib\http.js:568:28)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:8956) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
I haven't found much regarding the usage of Microsoft Edge in JS Selenium Grid, so I've come here to ask for help.
Any assistance would be appreciated!
EDIT
I tried using the Node Config as suggested by Yu Zhou, and am now getting a different error: UnhandledPromiseRejectionWarning: SessionNotCreatedError: Unable to create new service: EdgeDriverService
I attempted to use a different function that uses #microsoft/edge-selenium-tools instead of selenium-webdriver like so:
const edge = require("#microsoft/edge-selenium-tools");
let options = new edge.Options().setEdgeChromium(true);
let driver = new edge.Driver().createSession(options);
When run, this does create an Edge session, however I have not found a way to send this to my Selenium Grid. Can someone help me to do so, or offer guidance with the new error on my old code?

What is the Dockerfile to use node:12-alpine with puppeteer#1.19?

Since I faced puppeteer#1.13 error when printing pdf with lots of photos(at least need to renew the lock):
when running in Dev, there was exception:
(node:17) UnhandledPromiseRejectionWarning: Error: Page crashed!
at Page._onTargetCrashed (/usr/src/app/node_modules/puppeteer/lib/Page.js:176:24)
So I would like to use latest version of puppeteer#1.19. However, when I changed to use that, there is error :
Line239: await page.pdf({
path: TEMP_DIR + filename,
format: 'A4',
printBackground: true
});
printPdf() Error
Error: Protocol error (IO.read): Invalid parameters handle: string value expected
at /usr/src/app/node_modules/puppeteer/lib/Connection.js:183:56
at new Promise ()
at CDPSession.send (/usr/src/app/node_modules/puppeteer/lib/Connection.js:182:12)
at Function.readProtocolStream (/usr/src/app/node_modules/puppeteer/lib/helper.js:241:37)
at async Page.pdf (/usr/src/app/node_modules/puppeteer/lib/Page.js:988:12)
at async printPdf (/usr/src/app/puppeteer.js:239:9)
at async /usr/src/app/puppeteer.js:129:21
-- ASYNC --
at Page. (/usr/src/app/node_modules/puppeteer/lib/helper.js:111:15)
at printPdf (/usr/src/app/puppeteer.js:239:20)
at processTicksAndRejections (internal/process/task_queues.js:85:5)
at async /usr/src/app/puppeteer.js:129:21 {
message: 'Protocol error (IO.read): Invalid parameters handle: string value expected'
}
How can I prepare Dockerfile to support puppeteer#1.19 or solve this error? Thanks.

Cannot find module '../dialog' (Electron fatal error)

In electron, I encounter the following error:
module.js:440
throw err;
^
Error: Cannot find module '../dialog'
at Module._resolveFilename (module.js:438:15)
at Function.Module._resolveFilename (/opt/App/resources/electron.asar/common/reset-search-paths.js:47:12)
at Function.Module._load (module.js:386:25)
at Module.require (module.js:466:17)
at require (internal/module.js:20:19)
at Object.get [as dialog] (/opt/App/resources/electron.asar/browser/api/exports/electron.js:35:14)
at process.<anonymous> (/opt/App/resources/electron.asar/browser/init.js:64:31)
at emitOne (events.js:96:13)
at process.emit (events.js:188:7)
at process._fatalException (node.js:276:26)
It happens on a child process spawn that fails in Linux. Strange because I do have a try catch block around that, yet it still results in an uncaughtexception, as seen in the code in browser/init.js from electron.asar:
// Don't quit on fatal error.
process.on('uncaughtException', function (error) {
// Do nothing if the user has a custom uncaught exception handler.
var dialog, message, ref, stack
if (process.listeners('uncaughtException').length > 1) {
return
}
// Show error in GUI.
dialog = require('electron').dialog
stack = (ref = error.stack) != null ? ref : error.name + ': ' + error.message
message = 'Uncaught Exception:\n' + stack
dialog.showErrorBox('A JavaScript error occurred in the main process', message)
}
As said, my code is in a try catch:
try {
server = childProcess.spawn(java, ["-jar", "App.jar"], {
"cwd": serverDirectory,
"detached": true
}, function(err) {
console.log("in callback");
});
} catch (err) {
console.log("here we are");
console.log(err);
}
But neither the callback nor the catch block is reached. Any ideas what is going on here and why the default dialog module cannot be found?
I found same error with electron 1.6.2
Figured it was due, when closing the application an error occur and electron want to display it in a dialog, maybe the close process has started and electron can't load this module, anyway I add:
const { dialog } = require('electron');
in main.js, no more error in console instead a dialog the error, I can fix it, After that I let the require just in case.
I hope I understand your question correctly...
If by "default dialog module", you mean the electron dialog API, then you can require that like so: const { dialog } = require('electron'). (Or in pre-1.0 versions simply require('dialog'). See https://github.com/electron/electron/blob/master/docs/api/dialog.md
Also the try/catch needs to be around the require in the child process. The try/catch you have is around the spawning of the child process in the parent. That require is failing in an entirely different node.js process, so it's not caught in the parent process that spawned it. It sounds like your child process code might work better if it looked like:
try {
const dialog = require('dialog');
} catch(e) {}
Also, if childProcess.spawn is referring to the core node module child_process, that doesn't accept a callback function. See https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options
Can you share the code from your child process? That might help more.

Resources