ChromeOptions causes reference error using Selenium ChromeDriver for node.js - node.js

I am trying to use the ChromeDriver driver for Selenium to run some tests using Chrome, but I'm getting a reference error when I use ChromeOptions.
My Code
I want to force the use of certain options, such as testing it against a particular user profile. Based on the Selenium and ChromeDriver documentation, this is my file test.js:
opt = new chromeOptions(); // ERROR OCCURS HERE!
opt.setBinary("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");
opt.addArguments("--user-data-dir=C:\\Users\\MyUserAccount\\AppData\\Local\\Google\\Chrome\\User Data");
driver = new ChromeDriver(opt);
// rest of my script goes here
The error
I am executing this using the command node test.js. This throws the following error on the first line:
\path\to\test.js:1
ction (exports, require, module, __filename, __dirname) { opt = new chromeOpti
^
ReferenceError: chromeOptions is not defined
at Object.<anonymous> (\path\to\test.js:1:73)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
For what it's worth, if I skip setting options and replace the first four lines of the script with this, it works, but I can't set the options I need to set:
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
I'm sure that I'm missing something really basic, but I can't figure this one out. How can I set options for Chrome using Selenium and node.js?
Edited to remove some obviously invalid syntax from the samples in some of the documentation I found.

The following works for me:
var webdriver = require("selenium-webdriver");
var chrome = require("selenium-webdriver/chrome");
// Make sure the PATH is set to find ChromeDriver. I'm on a Unix
// system. You'll need to adapt to whatever is needed for
// Windows. Actually, since you say that you can get a browser to show
// up if you don't try to specify options, your ChromeDriver is
// probably already on your PATH, so you can probably skip this.
process.env["PATH"] += ":/home/user/src/selenium/";
var options = new chrome.Options();
// Commented out because they are obviously not what you want.
// Uncomment and adapt as needed:
//
// options.setChromeBinaryPath("/tmp/foo");
// options.addArguments(["--blah"]);
var driver = new webdriver.Builder().
withCapabilities(options.toCapabilities()).build();
driver.get("http://www.google.com")
I've tested the code above with various values and found that it works.
If you want to see what else you can do with the Options object, you can open node_modules/selenium_webdriver/chrome.js and read the source. This is how I figured out the above method.

could you please just try below solution
var webdriver = require("selenium-webdriver");
var chrome = require("selenium-webdriver/chrome");
/**
* Set chrome command line options/switches
*/
var chromeOptions = new chrome.Options();
chromeOptions.addArguments("test-type");
chromeOptions.addArguments("start-maximized");
chromeOptions.addArguments("--js-flags=--expose-gc");
chromeOptions.addArguments("--enable-precise-memory-info");
chromeOptions.addArguments("--disable-popup-blocking");
chromeOptions.addArguments("--disable-default-apps");
chromeOptions.addArguments("--disable-infobars");
driver = new webdriver.Builder()
.forBrowser("chrome")
.setChromeOptions(chromeOptions)
.build();
driver.get("http://www.google.com")

This works for me (from this gist)
//import the selenium web driver
var webdriver = require('selenium-webdriver');
var chromeCapabilities = webdriver.Capabilities.chrome();
//setting chrome options to start the browser fully maximized
var chromeOptions = {
'args': ['--test-type', '--start-maximized']
};
chromeCapabilities.set('chromeOptions', chromeOptions);
var driver = new webdriver.Builder().withCapabilities(chromeCapabilities).build();

This seems to be a fundamental OOP JavaScript misunderstanding!
Your problem is:
ChromeOptions opts = new chromeOptions();
You don't instantiate objects this way. Try:
var opt = new ChromeOptions();
Here's proof:
http://jsfiddle.net/q5Etk/
If you run that, we get "Unexpected Identifier".
Uncomment the var bit and comment the Cat cat bit and see it work.
EDIT After your edit:
You are specifying chromeOptions(). It's ChromeOptions() capped C

var m_Options = new chrome.Options();
m_Options.addArguments("--user-data-dir=C:/Users/israfil/AppData/Local/Google/Chrome/Profile 2");
m_Options.addArguments("--profile-directory=Default");
m_Options.addArguments("--disable-extensions");
m_Options.addArguments(['user-agent="Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.11 Safari/537.36"']);
m_Options.setBinaryPath("H://project//nodejs//chrome//chrome.exe");
m_Options.directConnect = false; //setBinaryPath true;
//m_Options.addExtensions();
//m_Options.setProxy();
//m_Options.headless();// Options.headless()}.#headless Options.headless()} Gpu Support ok
//m_Options.addArguments(" --blah"); // not use this codes Importent
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).setChromeOptions(m_Options).build();

Related

Synology NodeJS Selenium - Server terminated early with status 127

I read a lot of similar issue but nothing indicate works ...
I'm on Synology - DSM 7.1 (Debian) and my code is
const chrome = require('selenium-webdriver/chrome');
const chromedriver = require('chromedriver');
const webdriver = require('selenium-webdriver');
//const path = require('chromedriver').path;
const {By, until, Builder} = require('selenium-webdriver');
exports.getInfoFromUrl = async(url) => {
// Lancement du webdriver pour scrapper Bet Assistant
//let service = new chrome.ServiceBuilder().build();
//chrome.setDefaultService(service);
//var driver = new webdriver.Builder(path).withCapabilities(webdriver.Capabilities.chrome()).build();
const options = new chrome.Options();
options.addArguments(
'--no-sandbox',
'headless',
'disable-gpu',
'--disable-dev-shm-usage'
);
var driver = new webdriver.Builder(chromedriver.path)
//.forBrowser('chrome')
.withCapabilities(webdriver.Capabilities.chrome())
.setChromeOptions(options)
.build();
/*chrome.setDefaultService(new chrome.ServiceBuilder(chromedriver.path).build());
var driver = new webdriver.Builder(chromedriver.path)
.setChromeOptions(new chrome.Options().addArguments(['--no-sandbox','-headless', '--disable-dev-shm-usage']))
.build();
*/
driver.get(url);
}
When I execute this code with "node script.js" I get this error :
/volume1/web/betassistant/node_modules/selenium-webdriver/remote/index.js:248
reject(Error(e.message))
^
Error: Server terminated early with status 127
at /volume1/web/betassistant/node_modules/selenium-webdriver/remote/index.js:248:24
at processTicksAndRejections (node:internal/process/task_queues:96:5)
I try several sample or code to run webdriver but nothing works. I see some of user install "default-jre" (How do I solve "Server terminated early with status 127" when running node.js on Linux?) but I don't have "apt-get" and I think JRE don't be need on DSM.
Some help will be appreciate :)

Download plotly open source on node js

Can you download the entire module of plotly using node js. Right now, I am streaming data with plotly using node js by using my API keys. If there is a way, can yo give step by step instructions? I tried https://www.npmjs.com/package/plotly.js, but it does not work.
var plotly = require('plotly.js');
var initdata = [{x:[], y:[], stream:{token:'t2166m92ft', maxpoints:50}}];
var initlayout = {fileopt : 'overwrite', filename : 'nodenodenode5'};
plotly.plot(initdata, initlayout, function (err, msg) {
if (err) return console.log(err);
console.log(msg);
var stream1 = plotly.stream('t2166m92ft', function (err, res) {
if (err) return console.log(err);
console.log(res);
clearInterval(loop); // once stream is closed, stop writing
});
var i = 0;
var loop = setInterval(function () {
client.once('message', function (message) {
var data = { x : i , y : message.toString()};
var streamObject = JSON.stringify(data);
stream1.write(streamObject+'\n');
i++;
});
}, 5000);
});
}
when i tried install using npm install plotly.js, and ran my program I got :
\Users\intern\Documents\universal-ground-system\Node js\node_modules\plotly.js
rc\lib\index.js:397
var style = document.createElement('style');
^
ReferenceError: document is not defined
at Object.lib.addStyleRule (C:\Users\intern\Documents\universal-ground-syste
Node js\node_modules\plotly.js\src\lib\index.js:397:21)
at Object.<anonymous> (C:\Users\intern\Documents\universal-ground-system\Nod
js\node_modules\plotly.js\build\plotcss.js:61:16)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\Users\intern\Documents\universal-ground-system\Nod
js\node_modules\plotly.js\src\plotly.js:30:1)
at Module._compile (module.js:409:26)
Plotly open source library can not be used in node js. But can be used on client side javascript.
I got past this to some degree, but ran into another error, so close now it seems.
When I make a dom with jsdom it doesn't like to see window for some sort of async issue probably.
If you go into REPL load the file or otherwise get to make the new jsdom object, then you can do this sort of thing in REPL that references window and the needed document.
let jsdom = lib.require('jsdom');
//let window = (new jsdom.JSDOM('<p>Hello</p>')).window;
let dom = new jsdom.JSDOM('<p>Hello</p>');
/* While just testing I do this in REPL after .load index.js
let window = dom.window;
let document = window.document;
*/
So then I get a new error after npm install canvas that needs
apt-get install libcairo2-dev libjpeg8-dev libpango1.0-dev libgif-dev build-essential g++
first to properly build it on Ubuntu 16
so the new error is...
> let window = dom.window;
undefined
> let document = window.document;
undefined
>
>
> let plt = lib.require('plotly.js');
ReferenceError: self is not defined
at Object.254 (./node_modules/mapbox-gl/dist/mapbox-gl.js:509:29)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:735
at Object.252../window (./node_modules/mapbox-gl/dist/mapbox-gl.js:505:25)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:735
at Object.73.../package.json (./node_modules/mapbox-gl/dist/mapbox-gl.js:146:75)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at e (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:855)
>
I tried setting 'self' to 'document' and 'this' and get another error.
> self = document;
Document { location: [Getter/Setter] }
> plt = lib.plt = lib.require('plotly.js');
TypeError: Cannot read property 'hardwareConcurrency' of undefined
at Object.252../window (./node_modules/mapbox-gl/dist/mapbox-gl.js:505:834)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:735
at Object.73.../package.json (./node_modules/mapbox-gl/dist/mapbox-gl.js:146:75)
at s (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:684)
at e (./node_modules/mapbox-gl/dist/mapbox-gl.js:1:855)
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:873
at ./node_modules/mapbox-gl/dist/mapbox-gl.js:1:150
Next I attempted to get window.navigator into self but that's apparently got nothing to do with the error. Somewhere else in mapbox-gl.js is glitching out.
I've only found a reference to harwareConcurrency in mapboxgl.js here
https://github.com/mapbox/mapbox-gl-js/issues/899
Seems misleading to say it's a nodejs library when it only works in the browser? https://plot.ly/nodejs/
Just now I'm seeing something about an API Key? I guess I'm barking down the wrong tree sideways. Big mistake here.

'use-strict' enabled but not working in node

I have enabled use-strict mode in my .js file but when I run it, node keeps telling me that I don't have it enabled. PLEASE don't tell me to write "use-strict"; at the top of my file because I already tried that.
Here is my server.js file. I have been trying to see what is wrong but so far stack overflow has not been much help since most people seem to get this working on their first try.
require('use-strict')
'use-strict';
let util = require('util');
let http = require('http');
let Bot = require('#kikinteractive/kik');
var kik_username = process.env.KIK_USERNAME;
var kik_api_key = process.env.KIK_API_KEY;
var kik_baseUrl = process.env.KIK_BASEURL;
// Configure the bot API endpoint, details for your bot
let bot = new Bot({
username: kik_username,
apiKey: kik_api_key,
baseUrl: kik_baseUrl
});
bot.updateBotConfiguration();
bot.onTextMessage((message) => {
message.reply(message.body);
});
// Set up your server and start listening
let server = http.createServer(bot.incoming()).listen(8085);
Everything seems fine but when I run
$ node server.js
I keep getting this error
let util = require('util');
^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:148:18)
at node.js:405:3
It tells me to enable strict mode BUT I ALREADY DID THAT. I even required an npm package to make sure I was doing it right! Can anyone make sense of what is happening?
No dash in 'use strict'
'use strict' // not 'use-strict'
Check out the documentation for further reference
You don't need to require an npm package. just put "use strict"; at the top of the js file.

unit testing using phantomjs, selenium-webdriver,nodejs and chai-webdriver assertion lib

What I'm trying to do is to run small unit testing on my machine. I have all required node packages and phantomjs driver installed to my PATH.
var sw = require('selenium-webdriver');
var driver = new sw.Builder()
.withCapabilities(sw.Capabilities.phantomjs())
.build()
var chai = require('chai');
var chaiWebdriver = require('chai-webdriver');
chai.use(chaiWebdriver(driver));
driver.get("https://www.npmjs.org/package/chai-webdriver");
setTimeout(function(){
chai.expect('#content').dom.to.be.visible().then(function(){
console.log("content visible");
});
driver.quit();
},3000);
Running the above code,
node fileName.js
Gives me result like this.
/Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/webdriver/promise.js:1643
throw error;
^
Error: Selector #content matches nothing
at /Users/r558268/Documents/sandbox/node_modules/chai-webdriver/node_modules/webdriver-sizzle/lib/webdriver_sizzle.js:17:13
at /Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/goog/base.js:1243:15
at webdriver.promise.ControlFlow.runInNewFrame_ (/Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/webdriver/promise.js:1539:20)
at notify (/Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/webdriver/promise.js:362:12)
at notifyAll (/Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/webdriver/promise.js:331:7)
at resolve (/Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/webdriver/promise.js:309:7)
at reject (/Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/webdriver/promise.js:439:5)
at /Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/goog/base.js:1243:15
at webdriver.promise.ControlFlow.runInNewFrame_ (/Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/webdriver/promise.js:1539:20)
at notify (/Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/webdriver/promise.js:362:12)
==== async task ====
WebDriver.call(function)
at webdriver.WebDriver.call (/Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:517:15)
at webdriver.WebDriver.findElementInternal_ (/Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:728:15)
at webdriver.WebDriver.findElement (/Users/r558268/Documents/sandbox/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:706:17)
at one (/Users/r558268/Documents/sandbox/node_modules/chai-webdriver/node_modules/webdriver-sizzle/lib/webdriver_sizzle.js:15:22)
at /Users/r558268/Documents/sandbox/node_modules/chai-webdriver/lib/index.js:58:18
at Assertion.<anonymous> (/Users/r558268/Documents/sandbox/node_modules/chai-webdriver/lib/index.js:72:16)
at Assertion.ctx.(anonymous function) [as visible] (/Users/r558268/Documents/sandbox/node_modules/chai/lib/chai/utils/addMethod.js:40:25)
at null._onTimeout (/Users/r558268/Documents/sandbox/assertionExample.js:30:43)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
Now here is the thing.. if I save as the url npmjs.org/chai-webdriver onto my machine and run the same test, then it passes without any errors.
I'm not able to figure out why.. can anyone please help me out on this.. MUCH APPRECIATED! Thank you.

mongodb with nodejs

this is th code I am using inserting a document to mongodb.
var client = new Db('test', new Server("127.0.0.1", 27017, {}), {w: 1}),
test = function (err, collection) {
collection.insert({a:2}, function(err, docs) {
collection.count(function(err, count) {
test.assertEquals(1, count);
});
// Locate all the entries using find
collection.find().toArray(function(err, results) {
test.assertEquals(1, results.length);
test.assertTrue(results[0].a === 2);
// Let's close the db
client.close();
});
});
};
client.open(function(err, p_client) {
client.collection('test_insert', test);
});
but while running I am getting error
xports, require, module, __filename, __dirname) { var client = new Db('test',
^
ReferenceError: Db is not defined
at Object. (C:\Users\Basic node\cheerio\mongonode.js:1:81
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
can you suggest me how to solve this problem
thanks in advance
Please import all the required modules, which you are using. Db is not defined points out that Db is defined in some other module or you have forgot to declare it.
You'll notice this exact code block posted in a number of different stackoverflow questions. The problem here is that this is a copy and pasted code block from mongodb's documentation, as is in fact the first example of a mongodb nodejs program.
https://npmjs.org/package/mongodb
You'll find this under "Introduction" as "A simple example of inserting a document."
It's clearly an incomplete example, but a lot of people are just trying it out to see if they've got everything installed correctly and immediately run into a wall.
Most people will have installed the mongodb driver, but will be missing something at the top like this:
var mongodb = require('mongodb');
var Db = mongodb.Db;
var Server = mongodb.Server;
I also fell into the copy-paste trap here and ran into another issue with the "assertEquals" method not existing. I've seen other people reference that function in other places on the web, but not really sure how it works.
In any case, to make it work for me, I required the assert module:
var assert = require('assert');
And then I replaced the assertEquals lines with something like this:
assert.equal(1, count, "Unexpected result");
Note that you're going to run into an issue if you've run this a couple of times; it's going to count the number of things in that table, and there is going to be more than one.
You'll have to figure out how to get into mongo's CLI and remove them to get it to run successfully.
Try to install mongodb native driver
npm install mongodb

Resources