Skip to content

Instantly share code, notes, and snippets.

@Zren
Last active June 6, 2022 12:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Zren/4150939288687aef1fd9 to your computer and use it in GitHub Desktop.
Save Zren/4150939288687aef1fd9 to your computer and use it in GitHub Desktop.

Custom URL Schemes

This will tell you how to have browsers run command line commands when visiting urls with custom schemes custom://.

Steps

  1. Tell the browser how to handle the url scheme
  2. Tell the OS how to handle the url scheme
  3. Parse the url
  4. Run your command

1. Tell the browser how to handle the url scheme

Using javascript.

window.navigator.registerProtocolHandler(protocol, uri, title);

The protocol must be prefixed with web+ since it's not a whitelisted URL Scheme.

Example (apm://)
navigator.registerProtocolHandler('web+apm', 'apm://%s', 'Atom Package Manager');

2. Tell the OS how to handle the url scheme

Windows

http://msdn.microsoft.com/en-us/library/ie/aa767914(v=vs.85).aspx

Windows requires an empty URL Protocol key to flag that your entry is a URL Scheme handler.

First make a new key at HKEY_CLASSES_ROOT\custom where custom is your url scheme.

Second make a new key at HKEY_CLASSES_ROOT\custom\shell\open\command, and set the default value to your command. Use the %1 variable to pass the entire url to your command.

Example (echo://)
REGEDIT4

[HKEY_CLASSES_ROOT\echo]
@="URL:Echo In CMD Protocol"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\echo\shell\open\command]
@="cmd /k echo %1"
Example (apm://)

https://github.com/Zren/atom-misc/blob/master/assets/RegisterApmUrlScheme.reg

REGEDIT4

[HKEY_CLASSES_ROOT\apm]
@="URL:Atom Package Manager Protocol"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\apm\shell\open\command]
@="\"C:\\Program Files\\nodejs\\node.exe\" \"C:\\Users\\Admin\\.atom\\packages\\misc\\bin\\apmUriHandler.js\" \"%1\""

3. Parse the url

Remember that you are passed the entire url, and that it might not have the //. An example is the mailto scheme. Eg: mailto:admin@example.com.

Example (apm://)

NodeJS isn't the best tool to script in, but here's an example.

https://github.com/Zren/atom-misc/blob/master/bin/apmUriHandler.js

4. Run your command

The last step should have parsed the url, but unless it's executing your task, it's probably just the glue that launches your actual command with properly formatted parameters.

In The Wild

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment