I am quite new to writing Firefox Add-Ons, still, I got to a point where I patched together a working extension, except the very core of it.
At some point in the code, I need to execute a system-command on a file. I've found a snipped on the web and tried to adapt it, but without luck. From my xpi/components/script.js:
var cmd = '/usr/bin/somecommand'
var args = ['-option', 'value', f.path ];
var execFile = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
var process = Components.classes["#mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
execFile.initWithPath(cmd);
if (execFile.exists()) {
process.init(execFile);
process.run(false, args, args.length);
}
Can someone tell me what's wrong here? I've assembled the command and I've got the filename but I can't get Firefox to execute this code snippet.
Is this execFile, initWithPath, createInstance, etc. stuff really needed?? I just want to execute the command just like in the CLI:
$ somecommand -option value filename
Works fine for me with cmd and args changed to:
var cmd = '/usr/bin/say';
var args = ['hello', 'world' ];
As Neil says, we need more info for troubleshooting. Enable the Error Console and check if there are any messages there.
Related
I have created a node script which should run as a background process. Right after the script starts running run I need to get some user data (username & password).
After getting the user data I wish to close the terminal but the process should continue running in the background.
To complicate things, the node script is being built with pkg lib and will be started as an .exe
pkg on NPM
Here is a the code that will be executed:
async function init() {
try {
await fetchConfig();
const credentials = await getCredentials(); // this one prompts the request for user input
watchForNewFiles(credentials); // that one should use the credentials and continue running in the background.
} catch (e) {
console.error(e);
}
}
init();
Here's a solution:
// Neccesary libs
let fs = require("fs");
let child_process = require("child_process");
// Filename should end in .bat
let filename = "__tmp.bat";
// Main function, call this to prompt the values.
function prompt() {
// Write batch script
// Prompts 2 variables & writes them as JSON into the same file
fs.writeFileSync(filename,`#echo off
set /p Var1="Name: "
set /p Var2="Password: "
echo {"name": "%Var1%", "password": "%Var2%"} > ${filename}
exit`);
// Execute the script in a cmd.exe window & write the result into stdout & parse it as JSON
let result = JSON.parse(child_process.execSync(`start /w cmd /c ${filename} && type ${filename}`));
// Delete the file
fs.unlinkSync(filename);
return results;
}
// Example usage:
console.log(prompt()) // prints { name: 'hi', password: 'world' }
Tested as a node14-win-x64 pkg binary, works perfectly.
AFAIU this is not possible to do from inside node.js's running code by itself.
You have to use some kind of tool to put the node.js program in the background.
This answer lists several tools for this purpose.
This one is also useful.
I have spent some hours trying to search an element by id using appium javascript client with no luck. Have found some other posts here in stack overflow stating it works, but it doesn not work for me. It seems that I could use something like:
var buttonEl = await driver.findElement(By.id("resourceid"));
but I always get an error saying:
InvalidSelectorError: Locator Strategy 'css selector' is not supported for this session
Here the source code:
"use strict";
var wd = require("selenium-webdriver"),
By = wd.By,
until = wd.until;
// Setting Desired Capabilities.
var desiredCaps = {
platformName: "Android",
deviceName: "a3ae1c63",
appPackage: "com.mypackage",
appActivity: ".Main",
browserName: '',
noReset: true,
newCommandTimeout: 1000000
};
async function test() {
//Initiating the Driver
let driver = await new wd.Builder().usingServer("http://localhost:4723/wd/hub").withCapabilities(desiredCaps).build();
var buttonEl = await driver.findElement(By.id("id/contact_selector"));
buttonEl.click();
}
test();
I'm pretty confused now. I understand that it seems that I can't use the find element by id in an android session but on the other hand I have read about people using it successfully.
Any help would be greatly appreciated.
I think you are using selenium arguments for the locator strategy. Please readedocumentation of appium selector here http://appium.io/docs/en/commands/element/find-elements/index.html#selector-strategies.
try this
var buttonEl = await driver.element("id", "resource-id");
Finally I was able to fix my problem. The main problem was that I wasn't using the needed web driver. I switched to webdriverio and everything is working now.
Better place to start is to check examples in appium github. They have some examples for every driver. Code is a bit outdated though.
I have a basic piece of javascript that I am running from a .js on a windows desktop to retrieve data from https://lookup.binlist.net/ - when I run it I get a timeout on the GET line. I have looked at various solutions and not found anything that resolves my issue. Anyone got any ideas?
var urlb = "https://lookup.binlist.net/431940";
var xsh = new ActiveXObject("Msxml2.ServerXMLHTTP.6.0");
xsh.open("GET", urlb, false);
xsh.send();
I'm using CasperJS to test my webApp, the thing is that I need to access a DB to automatize some necessary inputs from my tests.
I'm looking for an alternatives on how to retrieve this data from the DB inside a casperJS js script an finally I decide to use phantomJS child process module to call a groovy script to connect a DB and make a select and print the result to stdout to get it from CasperJS. However from the sample of the phantomJS can not realize how to do it, based on the sample I made some attempts with spawn and execFile with no luck. i.e I try:
var process = require("child_process")
var spawn = process.spawn
var execFile = process.execFile
var child = spawn("groovy", ["script.groovy"])
child.stdout.on("data", function (data) {
console.log("spawnSTDOUT:", JSON.stringify(data))
})
child.stderr.on("data", function (data) {
console.log("spawnSTDERR:", JSON.stringify(data))
})
child.on("exit", function (code) {
console.log("spawnEXIT:", code)
})
This doesn't work and not produce any output. I also try directly executing dir command directly and also nothing happens.
I try also with linux and it doesn't work either, I try also creating a simple echo .sh and nothing..., however in linux when I try to run ls command this times it works as expected.
After some tries I found a way to do it.
Seems that in windows the only way to do it is passing cmd.exe as command and groovy script.groovy as argument.
So I use
var child = spawn("cmd.exe", ["/k","groovy script.groovy"])
instead of:
var child = spawn("groovy", ["script.groovy"])
This way works correctly on windows.
I also found the way to run a shell script on linux, which executes the groovy.It's similar to the windows solution, instead of invoke .sh I've to use sh command:
var child = spawn("sh", ["script.sh"])
And script.sh executes the groovy script:
#!/bin/bash
groovy script.groovy
I need to be able to run phantomjs with the following arg:
--ignore-ssl-errors=true
The page I'm testing uses a self-signed cert so I need the arg to open the page. I'm trying to pass the arg in webdriver using the snippet below:
capabilities = webdriver.Capabilities.phantomjs();
capabilities.set('service_args', '--ignore-ssl-errors=true');
driver = new webdriver.Builder().
withCapabilities(capabilities).
build();
Is the correct way to pass the service_args? I actually hope not since I can't load my test page. I can open the page by running:
phantomjs --ignore-ssl-errors=true myTest.js
Here is the code in myTest.js
var page = new WebPage();
page.open('https://my.somefaketestpage.com/', function (status) {
just_wait();
});
function just_wait() {
setTimeout(function() {
page.render('screenshot.png');
phantom.exit();
}, 2000);
}
The correct answer is:
caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true);
caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, new String[] {"--web-security=no", "--ignore-ssl-errors=yes"});
driver = new PhantomJSDriver(caps);
documented here: https://github.com/detro/ghostdriver/issues/233
In case someone will need it for facebook/php-webdriver CLI arguments can be passed to PhantomJS in a following manner:
$driver = RemoteWebDriver::create('http://localhost:4444/wd/hub', [
WebDriverCapabilityType::BROWSER_NAME => WebDriverBrowserType::PHANTOMJS,
WebDriverCapabilityType::PLATFORM => WebDriverPlatform::ANY,
'phantomjs.cli.args' => ['--ignore-ssl-errors=true']
]);
Reading this I got really confused, as the accepted answer is in Java, and the GhostDriver constants and stuff aren't present. For those who are also confused, this worked for me:
var webdriver = require('selenium-webdriver'),
Capabilities = webdriver.Capabilities;
var capability = Capabilities
.phantomjs()
.set('phantomjs.cli.args', '--ignore-ssl-errors=true');
var driver = new webdriver
.Builder()
.withCapabilities(capability)
.build();