Launch local executable from greasemonkey - javascript

Below is the code I am trying (plus a few variations), there is a dialog asking for my permission, but still errors out with
Error: Permission denied for to get property XPCComponents.classes
unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var file = unsafeWindow.Components.classes["#mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("d:\\test.bat");
var process = unsafeWindow.Components.classes["#mozilla.org/process/util;1"]
.createInstance(Components.interfaces.nsIProcess);
process.init(file);
var args = ["argument1", "argument2"];
process.run(false, args, args.length);
Is this just going to be impossible?

#Jano answer is right, but you can still invoke the .bat file using a custom protocol handler such as myprotocol://parameters. Also explained here: How to run local program (exe) via Chrome via HTML/javascript
Adding this keys to your registry:
HKEY_CLASSES_ROOT
myprotocol
(Default) = "URL:Test Protocol"
URL Protocol = ""
shell
open
command
(Default) = "d:\test.bat" "%1"
And inside the .bat to capture the parameter:
set param=%1
echo Parameter is "%param:~13,100%
Where :~13,100 Crops the first 13 characters of the parameter (myprotocol://)
Then in your script just use the custom protocol URL on window.location, $.ajax or assign to an <a>'s href.

You can't. See Do Greasemonkey scripts have chrome privileges?.

Related

How to check whether chrome browser is installed or not using java script?

My requirement is I need to check whether Chrome browser is insatlled on the client machine or not using Javascript. I have searched on the net not able to find the way out.
Please help in getting this done.
You can't do that with JavaScript, and even if you could, you shouldn't.
JavaScript on the client doesn't have access to the user's system, for very good reasons. (Think, servers with bad intentions.)
You can check if the browser is Chrome with the next code
if(!window.chrome){
//Chrome code
}else{
// Chrome block
}
You can't. Not with JavaScript. However, you can check whether the browser that is currently being used to view your webpage is Google Chrome or not.
<script type="text/javascript">
if(window.chrome){
document.write("Browser is Chrome");
}
else{
document.write("Please download Chrome");
}
</script>
You can't get that kind of information directly from javascript.
What you can do is use that PowerShell command in a script and save the result in a file that you'll read later using javascript.
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallLocation, Publisher, InstallDate | Format-Table -AutoSize
This will get you all the installed programs on the machine from the HKEY_LOCAL_MACHINE registry folder.
The exact path to the folder from wich the informations are retrieved is : HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\
The given command will display you the application name followed by it's version, it's install location, publisher name and installation date in a PowerShell terminal.
If you want to output that list in a file simply add >FileName.txt after the command before pressing enter.
Note that by default the file will be created in the C:\Users\YourUserName\ folder so if you want the file to be created in a specific location you'll have to use the CD command to get to that specific location before executing the Get-Item-Property command.
This will get you done for the get installed programs on a machine part.
Now we can get into the check if app x is installed on the machine part.
First load the previously generated file in your js application you will use it's content to determine if an application is installed on the computer.
The faster way to get if 'chrome' is installed will be to load the file as a string and then do that basic stuff :
if (string.includes('chrome') == true) {
// chrome is installed on the machine
// you can do some more stuff
// like extracting it's path from the file content
} else {
console.log('error: chrome is not installed on this computer');
}
Needless to say that this will only work if used on the same computer from which you want to check the installed applications.
Edit: If you want a more practical file to use in javascript you can replace
Format-Table -AutoSize >FileName.txt
with :
Export-Csv -path .\FileName.txt -NoTypeInformation
this way you can split your file lines using the string.split(',') method and don't have to do some extra stuff to deal with the spaces between data.
Edit 2:
Here's a full working implementation that will let you retrieve informations from a PowerShell script directly from your javascript using NodeJs.
get_programs.ps1 (PowerShell script file) :
chcp 65001 # sets the encoding for displaying chars correctly
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallLocation | ConvertTo-Csv -NoTypeInformation
chcp 850 # restores the default encoding set this will avoid police changes due to the terminal modifications
Notice the change at the end of the command which is now:
| ConvertTo-Csv -NoTypeInformation
this allows to log data in the PowerShell terminal in the csv format which will simplify it's parsing as a string.
If you don't want to use another file to hold those few PowerShell
commands you can use this
child = spawn("powershell.exe",[`chcp 65001
Get-ItemProperty HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | Select-Object DisplayName, DisplayVersion, InstallLocation | ConvertTo-Csv -NoTypeInformation
chcp 850`]);
as a replacement for
child = spawn("powershell.exe",["./get_programs.ps1"]);
If you choose to do this don't forget to escape the \ chars else it will not work.
app.js :
var spawn = require("child_process").spawn,child;
child = spawn("powershell.exe",["./get_programs.ps1"]); // here we start our PowerShell script "./" means that it's in the same directory as the .js file
let chromeDetails;
child.stdout.on("data", (data) => { // data event
// here we receive each outputed line in the PowerShell terminal as an Uint8Array
if (data.includes('Chrome')) { // check for the 'Chrome' string in data
chromeDetails = data.toString(); // adds data converted as string
}
});
child.stderr.on("data", (data) => { // logs errors
console.log(`Powershell Errors: ${data}`);
});
child.on("exit", () => { // exit event
console.log("Powershell Script finished");
if (chromeDetails != undefined) {
console.log(`> chrome has been detected on this computer
available informations (appName, version, installPath):
${chromeDetails}`);
} else
console.log('> chrome has not been detected on this computer');
});
child.stdin.end(); // we end the child
Expected output :
Powershell Script finished
> chrome has been detected on this computer
    available informations (appName, version, installPath):
    "Google Chrome","103.0.5060.114","C:\Program Files\Google\Chrome\Application"
If you are not on Windows you may want to take a look at Spawning .bat and .cmd files on Windows from the NodeJs documentation to get hints on how to adapt the above app.js code to work on your system.

How to fetch file content (basically read) a local file in javascript for UIAutomation iOS

Is there a possible way to read a local file in JavaScript.
MyFolder:
db.csv
Parse.js
Trying to fetch the contents of file db.csv in Parse.js, But in vain.
Can you share some links where I can get enough knowledge how to read a file.
Running Instruments in Xcode5, with test scripts in .js file where I have to feed in some values from a .csv file.
iOS UIAutomation, apple provides an api for running a task on the target's host.
performTaskWithPathArgumentsTimeout
Using this, we can have a bash script to printout the contents of a file that we wanted to fetch in the first case.
Bash script can be as simple as this for this requirement.
#! /bin/bash
FILE_NAME="$1"
cat $FILE_NAME
Save it as for example FileReader.sh file.
And in your automation script,
var target = UIATarget.localTarget();
var host = target.host();
var result = host.performTaskWithPathArgumentsTimeout(executablePath,[filePath,fileName], 15);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
where in,
executablePath is where the command need to be executed.
var executablePath = "/bin/sh";
filePath is the location of the created FileReader.sh file. When executed, outputs the content to standard output (in our requirement).
[give full absolute path of the file]
fileName is the actual file to fetch contents from.
[give full absolute path of the file] In my case I had a Contents.csv file, which I had to read.
and the last parameter is the timeout in seconds.
Hope this helps others, trying to fetch contents (reading files) for performing iOS UIAutomation.
References:
https://stackoverflow.com/a/19016573/344798
https://developer.apple.com/library/iOS/documentation/UIAutomation/Reference/UIAHostClassReference/UIAHost/UIAHost.html
If the file is on the same domain as the site you're in, you'd load it with Ajax. If you're using Ajax, it's be something like
$.get('db.csv', function(csvContent){
//process here
});
Just note that the path to the csv file will be relative to the web page you're in, not the JavaScript file.
If you're not using jQuery, you'd have to manually work with an XmlHttpRequest object to do your Ajax call.
And though your question doesn't (seem to) deal with it, if the file is located on a different domain, then you'd have to use either jsonP or CORS.
And, just in case this is your goal, no, you can't, in client side JavaScript open up some sort of Stream and read in a file. That would be a monstrous security vulnerability.
This is a fairly simple function in Illuminator's host functions library:
function readFromFile(path) {
var result = target.host().performTaskWithPathArgumentsTimeout("/bin/cat", [path], 10);
// be verbose if something didn't go well
if (0 != result.exitCode) {
throw new Error("readFromFile failed: " + result.stderr);
}
return result.stdout;
}
If you are using Illuminator, this is host().readFromFile(path).

How to translate wget command with custom header to vbscript or javascript?

For my html application I need to download JDK directly. This wget command seems to work for it
wget --no-cookies --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com" "http://download.oracle.com/otn-pub/java/jdk/7/jdk-7-linux-x64.tar.gz"
How can I translate this wget which is sending a custom header to ideally a vbscript line ( I prefer vbscript but will settle for javascript if i have to). P.S. I think the--no-cookies is optional but not sure. The reason I can't use a direct download link is that oracle requires users to click Accept Agreement on the download page below.
This link is for the latest download HTML page
http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html
and this is the latest direct .exe link ( once you have clicked ACCEPT AGREEMENT)
http://download.oracle.com/otn-pub/java/jdk/7u17-b02/jdk-7u17-windows-x64.exe
Or any other way to bypass the Accept Agreement problem?
This is my vbscript code which *gives an "unspecified error"*on line 4 with the setRequestHeader. the value ine gpw_e24 I tried the value i gave above too, didnt work.
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
URL="http://download.oracle.com/otn-pub/java/jdk/7u17-b02/jdk-7u17-windows-x64.exe"
saveto="c:\java.exe"
objXMLHTTP.setRequestHeader "Cookie", "gpw_e24=http%3A%2F%2Fwww.oracle.com"
objXMLHTTP.open "POST", URL, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0 'Set the stream position to the start
Set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.Fileexists(saveTo) Then objFSO.DeleteFile saveTo
Set objFSO = Nothing
objADOStream.SaveToFile saveTo
objADOStream.Close
Set objADOStream = Nothing
End if
Set objXMLHTTP = Nothing
' Done
WScript.Quit
To download the file you should add the request header with name Cookie and value gpw_e24=http%3A%2F%2Fwww.oracle.com
using code from vbscript to download a file (bypassing invalid certificate errors) you should try adding
xHttp.setRequestHeader "Cookie", "gpw_e24=http%3A%2F%2Fwww.oracle.com"
Alternatively you can take wget.exe with your script and call it
Download binaries package from http://gnuwin32.sourceforge.net/packages/wget.htm (you will need only wget.exe, there can be some required dll-s)
upd: Probably wget.exe from this binaries http://community.openscg.com/se/oscg_nixutils.jsp would be a better choice (because of no dependencies)
upd: I tried this, but oracle.com returns 403. Your WGET command also does not work.
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
URL="http://download.oracle.com/otn-pub/java/jdk/7u17-b02/jdk-7u17-windows-x64.exe"
saveto="c:\\Users\\Sanya_Zol\\INET_ALL\\2013\\_tmp\\20130326\\java-dl.exe"
objXMLHTTP.open "POST", URL, false
objXMLHTTP.setRequestHeader "Cookie", "gpw_e24=http%3A%2F%2Fwww.oracle.com%2Ftechnetwork%2Fjava%2Fjavase%2Fdownloads%2Fjdk7-downloads-1880260.html"
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0 'Set the stream position to the start
Set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.Fileexists(saveTo) Then objFSO.DeleteFile saveTo
Set objFSO = Nothing
objADOStream.SaveToFile saveTo
objADOStream.Close
Set objADOStream = Nothing
Set objXMLHTTP = Nothing
Else
MsgBox objXMLHTTP.Status
End if

Read local file in Phonegap

I'm trying to read a local file in Phonegap to load the language strings for the application and I can't make it work :(
The code is pretty straightforward:
var pathToLocalFile = "/home/user/android/assets/www/js/";
var langCache = new FileReader();
langCache.onload = function(data){
col = JSON.parse(data);
refreshAllStrings();
};
langCache.onerror = function(err){
debug.error(err);
};
langCache.readAsText(pathToLocalFile+currentLang+'.json');
This code doesn't work on the Ripple emulator and I replaced it with
var pathToLocalFile = "file:///android_asset/www/js/";
in case of android, with the same result:
Uncaught TypeError: Object #<Console> has no method 'warning' cordova-2.4.0.js:2616
initRead cordova-2.4.0.js:2616
FileReader.readAsText cordova-2.4.0.js:2660
loadLanguage
In the Ripple emulator, I started Chrome with google-chrome -–allow-file-access-from-files and the Android config and manifest has all the permissions for and the plugins set.
Of course I'm missing something, but any idea what this could be?
Regards.
If the file is under the www folder of your app you don't need to add '/home/..' or 'file:///'. You should just be able to load the contents using an "AJAX" fetch even though it is bundled in the app.
$.get('js/filename.ext');
The error you're seeing is actually a result of cordova-2.4.0.js calling a non-existent "warning" method. It should be console.warn. It is attempting to warn you that using a string for the readAsText method is now deprecated, and that you should use a File reference instead.
What should be happening is a console.warn of "Using a string argument with FileReader.readAs functions is deprecated."

Mozilla (Firefox, Thunderbird) Extension: How to get extension id (from install.rdf)?

If you are developing an extension for one of the mozilla applications (e.g. Firefox, Thunderbird, etc.) you define a extension id in the install.rdf.
If for some reason you need to know the extension id e.g. to retrieve the extension dir in local file system (1) or if you want to send it to a webservice (useage statistic) etc. it would be nice to get it from the install.rdf in favour to have it hardcoded in your javascript code.
But how to access the extension id from within my extension?
1) example code:
var extId = "myspecialthunderbirdextid#mydomain.com";
var filename = "install.rdf";
var file = extManager.getInstallLocation(extId).getItemFile(extId, filename);
var fullPathToFile = file.path;
I'm fairly sure the 'hard-coded ID' should never change throughout the lifetime of an extension. That's the entire purpose of the ID: it's unique to that extension, permanently. Just store it as a constant and use that constant in your libraries. There's nothing wrong with that.
What IS bad practice is using the install.rdf, which exists for the sole purpose of... well, installing. Once the extension is developed, the install.rdf file's state is irrelevant and could well be inconsistent.
"An Install Manifest is the file an Add-on Manager-enabled XUL application uses to determine information about an add-on as it is being installed" [1]
To give it an analogy, it's like accessing the memory of a deleted object from an overflow. That object still exists in memory but it's not logically longer relevant and using its data is a really, really bad idea.
[1] https://developer.mozilla.org/en/install_manifests
Like lwburk, I don't think its available through Mozilla's API's, but I have an idea which works, but it seems like a complex hack. The basic steps are:
Set up a custom resource url to point to your extension's base directory
Read the file and parse it into XML
Pull the id out using XPath
Add the following line to your chrome.manifest file
resource packagename-base-dir chrome/../
Then we can grab and parse the file with the following code:
function myId(){
var req = new XMLHttpRequest();
// synchronous request
req.open('GET', "resource://packagename-base-dir/install.rdf", false);
req.send(null);
if( req.status !== 0){
throw("file not found");
}
var data = req.responseText;
// this is so that we can query xpath with namespaces
var nsResolver = function(prefix){
var ns = {
"rdf" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"em" : "http://www.mozilla.org/2004/em-rdf#"
};
return ns[prefix] || null;
};
var parser = CCIN("#mozilla.org/xmlextras/domparser;1", Ci.nsIDOMParser);
var doc = parser.parseFromString(data, "text/xml");
// you might have to change this xpath expression a bit to fit your setup
var myExtId = doc.evaluate("//em:targetApplication//em:id", doc, nsResolver,
Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE, null);
return myExtId.singleNodeValue.textContent;
}
I chose to use a XMLHttpRequest(as opposed to simply reading from a file) to retrieve the contents since in Firefox 4, extensions aren't necessarily unzipped. However, XMLHttpRequest will still work if the extension remains packed (haven't tested this, but have read about it).
Please note that resource URL's are shared by all installed extensions, so if packagename-base-dir isn't unique, you'll run into problems. You might be able to leverage Programmatically adding aliases to solve this problem.
This question prompted me to join StackOverflow tonight, and I'm looking forward participating more... I'll be seeing you guys around!
As Firefox now just uses Chrome's WebExtension API, you can use #serg's answer at How to get my extension's id from JavaScript?:
You can get it like this (no extra permissions required) in two
different ways:
Using runtime api: var myid = chrome.runtime.id;
Using i18n api: var myid = chrome.i18n.getMessage("##extension_id");
I can't prove a negative, but I've done some research and I don't think this is possible. Evidence:
This question, which shows that
the nsIExtensionManager interface
expects you to retrieve extension
information by ID
The full nsIExtensionManager interface
description, which shows no
method that helps
The interface does allow you to retrieve a full list of installed extensions, so it's possible to retrieve information about your extension using something other than the ID. See this code, for example:
var em = Cc['#mozilla.org/extensions/manager;1']
.getService(Ci.nsIExtensionManager);
const nsIUpdateItem = Ci.nsIUpdateItem;
var extension_type = nsIUpdateItem.TYPE_EXTENSION;
items = em.getItemList(extension_type, {});
items.forEach(function(item, index, array) {
alert(item.name + " / " + item.id + " version: " + item.version);
});
But you'd still be relying on hardcoded properties, of which the ID is the only one guaranteed to be unique.
Take a look on this add-on, maybe its author could help you, or yourself can figure out:
[Extension Manager] Extended is very
simple to use. After installing, just
open the extension manager by going to
Tools and the clicking Extensions. You
will now see next to each extension
the id of that extension.
(Not compatible yet with Firefox 4.0)
https://addons.mozilla.org/firefox/addon/2195

Categories

Resources