Connect to geckodriver with selenium js - selenium

I'm not an expert of Selenium, so I may miss something here.
One of the software in the corp starts a firefox with Geckodriver.
I would like to connect / attach to this browser from my JavaScript code.
I know the port where the Webserver starts and the sessions identifier.
I try to connect from JS:
const webdriver = require('selenium-webdriver')
void async function() {
let driver = await new webdriver.Builder().forBrowser('firefox').usingServer('http://localhost:55849/').build();
await driver.get('http://www.google.com/ncr');
await driver.findElement(By.name('q')).sendKeys('webdriver');
await driver.findElement(By.name('btnG')).click();
await driver.wait(until.titleIs('webdriver - Google Search'), 1000);
driver.quit();
}();
The connection is not successful. What I can think is that this code tries to start a new instance.
There is an error message:
SessionNotCreatedError: Session is already started
Any idea how I can connect to the existing one? And control it?
I've tried everything from the docs: https://www.npmjs.com/package/selenium-webdriver
I even tried to connect http://localhost:55849/wd/hub but then I received WebDriverError: HTTP method not allowed error

Use the selenium-webdriver/http
const webdriver = require('selenium-webdriver')
const http= require('selenium-webdriver/http')
let sessionId = '9aad751d-eb9b-4c92-92f3-298c733f6ec7';
let url = 'http://localhost:57538';
let driver = new webdriver.WebDriver(
sessionId,
new http.Executor(Promise.resolve(url)
.then(
url => new http.HttpClient(url, null, null))
)
);

Related

xhr to service with windows authentication

To access in browser web service using windows authentication I add the following:xhr.withCredentials= true;
Is it enough? Sometimes browser still shows windows asking for user win credentials. More details.
https://localhost:44386/api uses windows auth. Some users are allowed, some not - for test. Here is js code. Is it ok? Sometimes users still get dialog asking for teir windows credentials.
function send() {
const url = 'https://localhost:44386/api/values';
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("GET", url);
xhr.onload = () => requestComplete(xhr);
xhr.send();
};

Vue mqtt throws an error as ws does not work in the browser

I am really new to vue and for this project I am trying to connect my code with MQTT HOST URL ws://21.17.0.1:9009/. When I use the same code and run on local laptop as from XAMP LOCALHOST, it works fine without any error. When I push the code to my company server and try to run the same code then it throws me an error as ws does not work in the browser. Browser clients must use the native WebSocket object. Is it because I am defining ws url inside mqtt.connect?
SCRIPT
runMqtt() {
var mqtt = require('mqtt');
var client = mqtt.connect('ws://21.17.0.1:9009/');
}
client.on('connect', function () {
client.subscribe('route_status', function (err) {
if (!err) {
client.publish('presence', 'Hello mqtt')
}
})
})
var message = {command: "tap", route_status: "TRUE"};
var obj = JSON.stringify(message);
client.publish('server_commands', obj, {qos: 1});
Not sure if the mqtt.js code supports WebSockets in a brower (as your error message states.) You might want to try Steve's tutorial: http://www.steves-internet-guide.com/using-javascript-mqtt-client-websockets/ ...which uses a different library to do ws from a browser. Or... just try a different method like 'mqtt://' or 'tcp://'

Preserving cookies between sessions

I need to make sure that a browser is trusted every time the session is when performing Selenium script in Node.js (If the browser is not trusted by the server it resets in MFA with SMSes which I would like to avoid).
In Puppeteer it is simple by:
const browser = await puppeteer.launch({headless: false,
userDataDir: "./user_data"});
I would love to stay with puppeteer because of that but I have a dropdown selector on the page accessible only by name or xpath and page and page.select requires CSS selector:-(.
So I moved back to Selenium, but there I have this persistency problem:
At the end of a session I have:
var allCokies = await driver.manage().getCookies(); fs.writeFile("/Users/matnikr/Documents/scrape/selenium/cookies.json",JSON.stringify(allCokies), function(err){
if (err) {return console.log(err)}
console.log('file saved');})
A the begining I have:
driver = await new Builder().forBrowser('chrome').build();
var allCokies = JSON.parse(fs.readFileSync("/Users/matnikr/Documents/angular\ code/Aliorscrape/selenium/cookies.json","utf8"));
for (var key in allCokies){
await driver.manage().addCookie(allCokies[key])
}
await driver.get('https:*******/do/Login');
And every time it feels like "incognito" session is started. Browser is untrusted. Any help appreciated.
Did you try to do the same as you did with Puppeteer? I mean to load a profile. Because it's actually what you did by providing "./user_data" as a userDataDir value.
const { Builder } = require('selenium-webdriver');
const { Options } = require('selenium-webdriver/chrome');
function buildChromeDriver() {
const options = new Options();
options.addArguments('user-data-dir=./user_data');
return new Builder()
.forBrowser('chrome')
.setChromeOptions(options)
.build();
}
You can always verify the loaded profile by opening chrome://version in the browser:
driver.get('chrome://version');

jMeter - Selenium integration

I have jMeter test case already written, it has requests for logging in and some POST requests to my table.
Now I want to measure render time of the page (response of the POSTS).
I want to use Selenium so I read:
Running Selenium scripts with JMeter
The problem is that i want Selenium to use the same session (in other words: to be already logged in) as logging in was handled by jMeter already.
How can i archive that ?
My TestPlan:
[UPDATE]
#Dmitri T
Thanks for answer! I did what you have suggested but it still don't work. Maybe I am doing something wrong but still just after Selenium opens browser it goes to login page. I put JSR223 PostProcessor under my LOGIN POST request and this is my WebDriver Sampler:
var pkg = JavaImporter(org.openqa.selenium);
var support_ui = JavaImporter(org.openqa.selenium.support.ui.WebDriverWait);
var wait = new support_ui.WebDriverWait(WDS.browser, 5000);
WDS.sampleResult.sampleStart();
WDS.sampleResult.getLatency();
WDS.log.info("Sample started");
WDS.browser.get(WDS.parameters);
WDS.log.info("LOGGING INTO: " + (WDS.parameters))
var cookieManager = WDS.vars.getObject('cookieManager')
for (var i=0; i < cookieManager.getCookieCount(); i++) {
var jmeterCookie = cookieManager.getCookies().get(i)
var seleniumCookie = new org.openqa.selenium.Cookie(jmeterCookie.name, jmeterCookie.value, jmeterCookie.domain, jmeterCookie.path, java.util.Date.from(java. time.Instant.ofEpochMilli(jmeterCookie.expiresMillis)), jmeterCookie.secure)
WDS.browser.manage().addCookie(seleniumCookie)
}
java.lang.Thread.sleep(5000)
WDS.sampleResult.sampleEnd();
{UPDATE 2}
Ok, i think that htere is something wrong with Cookies in all Thread Group.
I have [no cookies] on every request:
In order to pass the "session" you need to copy all the cookies from JMeter's HTTP Cookie Manager into the Selenium session.
This can be done in the WebDriver Sampler directly as follows:
Add JSR223 PostProcessor as a child of the request which session you want to copy
Put the following code into "Script" area
vars.putObject('cookieManager', sampler.getCookieManager())
it will store the current state of the HTTP Cookie Manager into JMeter Variables
In the WebDriver Sampler you can copy the cookies from the HTTP Cookie Manager and add them to the WebDriver instance using WDS.browser.manage().addCookie() function as follows:
var cookieManager = WDS.vars.getObject('cookieManager')
for (var i=0; i < cookieManager.getCookieCount(); i++) {
var jmeterCookie = cookieManager.getCookies().get(i)
var seleniumCookie = new org.openqa.selenium.Cookie(jmeterCookie.name, jmeterCookie.value, jmeterCookie.domain, jmeterCookie.path, java.util.Date.from(java.time.Instant.ofEpochMilli(jmeterCookie.expiresMillis)), jmeterCookie.secure)
WDS.browser.manage().addCookie(seleniumCookie)
}

OpenTok - Subscriber failed to subscribe to a stream in a reasonable amount of time

I am implementing a Network Test for my Web-application using OpenTok's js library.
To do that, I create a publisher, connect to session, then make a subscriber connect to the publisher's stream.
The Test is working on other browsers (I have tested Chrome and Internet Explorer) but on Firefox version 57.0.1 I get an error - 'The stream was unable to connect due to a network error. Make sure you have a stable network connection and that it isn't blocked by a firewall.'
Make sure when you create the OpenTok Session you are using a 'routed' Session, not a 'relayed' one. Also make sure you are passing the 'testNetwork' property to the subscribe method. Here is a working sample:
// Sample code
var session = OT.initSession(APIKEY, SESSIONID);
session.connect(TOKEN, function(err) {
if (err) {
alert(err.message);
return;
}
var publisher = session.publish();
publisher.on('streamCreated', function(event) {
session.subscribe(event.stream, null, {
testNetwork: true
}, function(err) {
if (err) alert(err.message);
});
});
});
https://jsbin.com/quruzac/edit