Is there any way to get command line parameters in Google Chrome extension? Is there any way to get command line parameters in Google Chrome extension? google-chrome google-chrome

Is there any way to get command line parameters in Google Chrome extension?


Hack alert: this post suggests passing a fake URL to open that has all the command-line parameters as query string parameters, e.g.,

chrome.exe http://fakeurl.com/?param1=val1&param2=val2


Perhaps pass the path to your extension in a custom user agent string set via the command line. For example:

chrome.exe --user-agent='Chrome 43. My path is:/path/to/file'

Then, in your extension:

var path = navigator.userAgent.split(":");console.log(path[1])


Basically I use the technique given in @dfrankow's answer, but I open 127.0.0.1:0 instead of a fake URL. This approach has two advantages:

  1. The name resolution attempt is skipped. OK, if I've chosen the fake URL carefully to avoid opening an existing URL, the name resolution would fail for sure. But there is no need for it, so why not just skip this step?
  2. No server listens on TCP port 0. Using simply 127.0.0.1 is not enough, since it is possible that a web server runs on the client machine, and I don't want the extension to connect to it accidentally. So I have to specify a port number, but which one? Port 0 is the perfect choice: according to RFC 1700, this port number is "reserved", that is, servers are not allowed to use it.

Example command line to pass arguments abc and xyz to your extension:

chrome "http://127.0.0.1:0/?abc=42&xyz=hello"

You can read these arguments in background.js this way:

chrome.windows.onCreated.addListener(function (window) {    chrome.tabs.query({}, function (tabs) {        var args = { abc: null, xyz: null }, argName, regExp, match;        for (argName in args) {            regExp = new RegExp(argName + "=([^\&]+)")            match = regExp.exec(tabs[0].url);            if (!match) return;            args[argName] = match[1];        }        console.log(JSON.stringify(args));    });});

Console output (in the console of the background page of the extension):

{"abc":"42","xyz":"hello"}