Why I get chrome launch error, when I export some data with html-to-xslx package in node js - html

When I try to export data with html-to-xslx npm package, this message displayed:
Error: Failed to launch chrome!
[0221/145806.785119:ERROR:zygote_host_impl_linux.cc(89)] Running as
root without --no-sandbox is not supported. See
https://crbug.com/638180.TROUBLESHOOTING:
https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md

If we want to lunch chrome with root privilege, we must add --node-sandbox in 'chrome-page-eval' constructor: launchOptions: {headless: true, args:['--no-sandbox']}
Here is a full example:
const conversionFactory = require('html-to-xlsx');
const chromeEval = require('chrome-page-eval')({ puppeteer, launchOptions: {headless: true, args:['--no-sandbox']} });
const conversion = conversionFactory({
extract: chromeEval
})
This way worked for me

Related

Cypress throwing SecurityError

I am currently running with Chrome 74 and trying to use Cypress to test a style-guide in my app. When I load up Cypress it throws this error:
SecurityError: Blocked a frame with origin "http://localhost:3000"
from accessing a cross-origin frame.
Please let me know if there is a solution to this!
I had tried to follow along with this:
https://github.com/cypress-io/cypress/issues/1951
But nothing has changed/worked for me. :(
My code is shown below: cypress/plugins/index.js
module.exports = (on, config) => {
on('before:browser:launch', (browser = {}, args) => {
// browser will look something like this
// {
// name: 'chrome',
// displayName: 'Chrome',
// version: '63.0.3239.108',
// path: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
// majorVersion: '63'
// }
if (browser.name === 'chrome') {
args.push('--disable-site-isolation-trials');
return args
}
if (browser.name === 'electron') {
args['fullscreen'] = true
// whatever you return here becomes the new args
return args
}
})
}
in my cypress/support/index.js
This will load the site before every test I run to save myself from having to write cy.visit in every test.
beforeEach(() =>{
cy.visit('http://localhost:3000/style-guide')
})
I had the very same issue yesterday and the answer from #jsjoeio in the cypress issue #1951 you've referenced in your question actually helped me.
So basically only thing I've done was to modify my cypress.json and add following value:
{
"chromeWebSecurity": false
}
You can disable security to overcome this issue.
Go to cypress.json file.
Write { "chromeWebSecurity": false } and save.
Run the test again.
I had exactly the same problem, I advise you to do as DurkoMatko recommends. Documentation chromeWebSecurity
But I encountered another problem with a link pointing to localhost in an iframe.
If you want to use a link in an iframe I recommend this :
cy.get('iframe').then((iframe) => {
const body = iframe.contents().find('body');
cy.wrap(body).find('a').click();
});
I have also faced this issue. My application was using service workers. Disabling service workers while visiting a page solved the issue.
cy.visit('index.html', {
onBeforeLoad (win) {
delete win.navigator.__proto__.serviceWorker
}
})
Ref: https://glebbahmutov.com/blog/cypress-tips-and-tricks/#disable-serviceworker
So, at least for me, my further problem was an internal one with tokens, logins, etc. BUT!
the code I posted for how the index in the plugin folder is correct to bypass the chrome issue. That is how you want to fix it!
Goto your cypress.json file.
Set chrome web security as false
{
"chromeWebSecurity": false
}
To get around these restrictions, Cypress implements some strategies involving JavaScript code, the browser's internal APIs, and network proxying to play by the rules of same-origin policy.
Acess your project
In file 'cypress.json' insert
{
"chromeWebSecurity": false
}
Reference: Cypress Documentation

How do I get actual config in puppeteer?

I want to conditionally execute some code based on the headless config attribute in puppeteer (passed in the .launch function).
e.g. : when I use the .type function, if it is running with headless: true, I don't want any delay. Else, add some { delay: 200 }.
How can I retrieve the headless value from the config?
Edit (thanks to #AndreyLushnikov comment)
You can figure out if puppeteer runs (non-)headless at runtime by checking browser.process() spawnargs for --headless switch with which Chromium were (or not) launched:
const headless = browser.process().spawnargs.includes("--headless") ? true : false;
console.log("Headless? " + headless);
With the latest puppeteer version to date (1.7.0), this is how I retrieved the config :
const client = await page.target().createCDPSession();
const response = await client.send('Browser.getBrowserCommandLine');
page.headless = response.arguments.includes('--headless');
See this github issue for more information

Cannot read property on of undefined. Electron BrowserWindow object

I am trying to learn Electron, but am running into an issue with the Pluralsight tutorial I am using. I installed the 'electron-prebuilt' module. I get an error everytime I run "npm start". The window opens as expected, but the error message that pops up in a dialog box kind of ruins the whole thing. Here is the error:
Uncaught Exception:
TypeError: Cannot read property 'on' of undefined at Object.
There's more to the long error message but it won't let me copy and paste, and the rest of the error just refers to the location of the supposed problem on line 14 of my main.js code. Here is my main.js file:
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
let mainWindow
app.on('ready', _ => {
mainWindow = new BrowserWindow({
height: 400,
width: 400
})
})
mainWindow.on('closed', _ => {
console.log('closed')
mainWindow = null
})
It's indicating that the BrowserWindow object I created doesn't have an "on" method, but I know this to be false per the Electron documentation:
https://electronjs.org/docs/api/browser-window
So I'm thinking that the value of mainWindow just isn't being set. I could try instantiating mainWindow with a new BrowserWindow object at the time I declare it, but I get an error message if I try that indicating that I can only instantiate BrowserWindow objects in ready functions.
you have to understand how callbacks work in node.js, callbacks are executed asynchronously, before app.onready fires, mainWindow is still undefined hence the declaration of let mainWindow assigns undefined to mainWindow, take mainWindow.on("closed", ....) into the app.on("ready") event handler. Do this
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
let mainWindow
app.on('ready', _ => {
mainWindow = new BrowserWindow({
height: 400,
width: 400
})
mainWindow.on('closed', _ => {
console.log('closed')
mainWindow = null
})
})
This error also occurs if you are just calling node on your electron script instead of electron. Your npm start script should be calling npx electron . instead, so try running npx electron . or npx electron main.js first. See this relevant issue here:
https://github.com/electron/electron/issues/7475

Gulp-octo is ignoring my choice of output directory

I'm trying to build an Octopus Deploy package for an angular-cli project using Gulp and Gulp-Octo:
const gulp = require("gulp"),
octopus = require("#octopusdeploy/gulp-octo"),
version = require("./package.json").version;
gulp.task("octopack",
["build-prod"],
() => gulp.src("dist/*")
.pipe(octopus.pack(
"zip", // octopackjs does not support nupkg format yet
{
id: "myprojectid",
version: `${version}.${commandLineOptions.buildnumber}`
}))
.pipe(gulp.dest('./octopus'))
);
This creates a package with the correct contents and version number, but it always goes into the current directory (alongside gulpfile.js) instead of the directory that I specified in gulp.dest().
I have tried all of the following variations in the call to gulp.dest, with the same result:
./octopus
./octopus/
octopus/
octopus
path.join(__dirname, 'octopus')
Am I misunderstanding how gulp.dest() works, or is octopus.pack() doing something weird?
(Note: If I leave out the gulp.dest() altogether then no zip file is created.)
It's a bug in gulp-octo. In this line they set the path of the generated archive. Unfortunately they just use the filename of the archive instead of a full path (which is what they're supposed to do), so the file is always written relative to the current working directory.
I might send them a pull request when I get the chance, since this is an easy fix.
In the meantime you can use the following workaround:
var path = require('path');
gulp.task("default",
() => gulp.src("dist/*")
.pipe(octopus.pack(
"zip", // octopackjs does not support nupkg format yet
{
id: "myprojectid",
version: `${version}.${commandLineOptions.buildnumber}`
}))
.on('data', (f) => { f.path = path.join(f.base, f.path) })
.pipe(gulp.dest('./octopus'))
);

Polymer: two gulp errors at build time: 'async completion' and 'apply' property

I'm trying to run gulp to build my app like Rob Dodson explains here.
Original error
At the command line, if I run:
npm run build
I get the following error:
[20:50:55] Using gulpfile ~/path/to/gulpfile.js
[20:50:55] Starting 'default'...
Deleting build/ directory...
[20:50:56] The following tasks did not complete: default
[20:50:56] Did you forget to signal async completion?
It appears there is some task described as "signal async completion?" What does this mean? And how do I do it?
Alternate error
However if I run the following at the command line:
gulp
I get a different error message as follows:
[23:40:57] Using gulpfile ~/path/to/gulpfile.js
/usr/local/lib/node_modules/gulp/bin/gulp.js:129
gulpInst.start.apply(gulpInst, toRun);
^
TypeError: Cannot read property 'apply' of undefined
at /usr/local/lib/node_modules/gulp/bin/gulp.js:129:19
at nextTickCallbackWith0Args (node.js:420:9)
at process._tickCallback (node.js:349:13)
at Function.Module.runMain (module.js:443:11)
at startup (node.js:139:18)
at node.js:968:3
Why would there be different error messages? Does that give a hint what's actually causing the errors? If so, what is it? And what can I do to fix it?
My code
I just copied the files package.json, polymer.json and gulpfile.js from the sample code Rob supplied here. Then I ran npm install as this answer describes.
gulpfile.js
'use strict';
// Documentation on what goes into PolymerProject.
const path = require('path');
const gulp = require('gulp');
const mergeStream = require('merge-stream');
const del = require('del');
const polymerJsonPath = path.join(process.cwd(), 'polymer.json');
const polymerJSON = require(polymerJsonPath);
const polymer = require('polymer-build');
const polymerProject = new polymer.PolymerProject(polymerJSON);
const buildDirectory = 'build/bundled';
/**
* Waits for the given ReadableStream
*/
function waitFor(stream) {
return new Promise((resolve, reject) => {
stream.on('end', resolve);
stream.on('error', reject);
});
}
function build() {
return new Promise((resolve, reject) => {
// Okay, so first thing we do is clear the build
console.log(`Deleting build/ directory...`);
del([buildDirectory])
.then(_ => {
// Okay, now lets get your source files
let sourcesStream = polymerProject.sources()
// Oh, well do you want to minify stuff? Go for it!
// Here's how splitHtml & gulpif work
.pipe(polymerProject.splitHtml())
.pipe(gulpif(/\.js$/, uglify()))
.pipe(gulpif(/\.css$/, cssSlam()))
.pipe(gulpif(/\.html$/, htmlMinifier()))
.pipe(polymerProject.rejoinHtml());
// Okay now lets do the same to your dependencies
let depsStream = polymerProject.dependencies()
.pipe(polymerProject.splitHtml())
.pipe(gulpif(/\.js$/, uglify()))
.pipe(gulpif(/\.css$/, cssSlam()))
.pipe(gulpif(/\.html$/, htmlMinifier()))
.pipe(polymerProject.rejoinHtml());
// Okay, now lets merge them into a single build stream.
let buildStream = mergeStream(sourcesStream, depsStream)
.once('data', () => {
console.log('Analyzing build dependencies...');
});
// If you want bundling, do some bundling! Explain why?
buildStream = buildStream.pipe(polymerProject.bundler);
// If you want to add prefetch links, do it! Explain why?
// buildStream = buildStream.pipe(new PrefetchTransform(polymerProject));
// Okay, time to pipe to the build directory
buildStream = buildStream.pipe(gulp.dest(buildDirectory));
// waitFor the buildStream to complete
return waitFor(buildStream);
})
.then(_ => {
// You did it!
console.log('Build complete!');
resolve();
});
});
}
gulp.task('default', build);
The original error is unrelated to the "alternate error".
While the build task runs gulp, npm run prioritizes the locally-installed gulp (at node_modules/.bin/gulp) before the system-installed gulp. Running gulp yourself (without npm run) would invoke the globally-installed gulp, which may result in an error if it's incompatible with your project (e.g., Gulp 3 binary with Gulp 4 API in your scripts, which appears to be the case). You could either install Gulp 4 so that you can run gulp yourself, or continue using npm run build.
To troubleshoot the original error, I recommend starting from the Polycast's original source (if you haven't already) to determine what the difference could be.
If you prefer to stick with your current track, I suggest a few things:
Verify the paths in your HTML imports, as a path to a non-existent file would cause a silent error (polymer-build issue 88). It might be helpful to run polymer build -v (verbose build).
Add buildStream.on('error', (err) => console.log(err)) after let buildStream = ... in case any unsuppressed error events crop up in that stream.
I recommend you use the new version of PSK Custom Build:
https://github.com/PolymerElements/generator-polymer-init-custom-build/
It has the gulpfile.js updated.
The problem was caused by an incorrect import path.
incorrect path
<link rel="import" href="../../../bower_components/polymer/polymer.html">
correct path
<link rel="import" href="../../bower_components/polymer/polymer.html">
As #tony19, correctly described, that errant import path caused a silent failure.
I found this by pursuing the path suggested by #abdonrd. I followed the instructions here as follows.
First, I copied my project. Then I loaded into the my-app directory per the below described procedure.
https://github.com/PolymerElements/generator-polymer-init-custom-build/
npm install -g polymer-cli
npm install -g generator-polymer-init-custom-build
mkdir my-app
cd my-app
polymer init custom-build
polymer build -v # the results of this command highlighted my error in red
The error showed the path of the missing file. Which I noticed was located one level higher than it should have been because the root directory my-app/ was missing from the path. Then I had to search manually through all the files using the search string polymer/polymer.html until I found a mismatch between the number of ../ in the import path (3 in this case) and the number of folders deep into the root directory the importing file was (2 in this case).
After I corrected the file path, I again ran:
polymer build -v # building the project again, correctly this time
polymer serve build/bundled # to test serve the build/bundled version