Due to an architecture I must work with that likely breaks a lot of very good software design rules, I need to send a message from some javascript code running in a web browser to a windows batch file on the same machine. The operating systems is Windows Vista or later. The browsers being used are primarily Chrome and Firefox. jQuery is also being used with the javascript.
The browser is connected to the internet and their is a server involved, so I could relay the message to the server, and then to the batch file. Right now I have a batch file that runs every minute or so that could theoretically query the server for any messages. Other than that, I don’t have any good ideas.
Additionally, this is a “closed” system. The client browser, client system, and server are under my complete control. It is not a situation where the general public is running the Javascript in their browser. The the client computer can be manipulated to be able to receive the message.
What is a good way to send this message?
1. Local HTTP server
From JavaScript, send AJAX request containing your command to local HTTP server. All modern browsers support cross-domain AJAX. The server can pass command as a parameter to the batch file. Make sure that the server is not accessible from network.
The advantage of this approach is that you can send response from command back to JavaScript.
JavaScript:
Bottle.py server:
Or PHP under Apache/nginx:
Or daemon in PHP:
For extra fun it has full shell access and can run commands asynchronously, which allows to launch desktop applications without blocking. It doesn’t need Apache.
Start:
php.exe -f batrunner_daemon.phpUse:
$.get('http://localhost:33333/ping -h', function(response) { console.log(response) });To keep it simple, it doesn’t have proper error handling and allows any site to execute anything on your computer, use at your own risk.
Access-Control-Allow-Origin: *means that any site can receive response from shell. Without this header they obviously still can run commands, but can’t receive response.2. URI Scheme
I experimented with @mamdrood’s idea, and it turned out to be very simple, much easier than HTTP server.
From HTML, you’ll be able to call the batch file like this:
And here’s how the batch file in
C:\mybatfile.batcan parse commands:I’m not very familiar with batch files, and my command name parsing code can be vulnerable. If you know any better please update this answer.
To associate your batch file with
batrunner://protocol createbatrunner.regand run it once. SubstituteC:\\mybatfile.batfor your script, path should be escaped.