113

如何在 Windows 中注册自定义协议,以便在单击电子邮件或网页中的链接时打开我的应用程序并将 URL 中的参数传递给它?

4

3 回答 3

103
  1. 然后Start输入Find类型regedit->它应该打开Registry editor

  2. Right Mouse然后点击HKEY_CLASSES_ROOT- New>Key

在此处输入图像描述

  1. 在 Key 中给出您希望调用 url 的小写名称(在我的情况下它将是)testus://sdfsdfsdf然后单击-> 然后->并添加没有值。Right MousetestusNewString ValueURL Protocol

在此处输入图像描述

  1. 然后像使用协议(Right Mouse New-> Key)一样添加更多条目,并创建像testus-> shell-> open->这样的层次结构command,并在内部command更改(Default)要启动的路径.exe,如果要将参数传递给 exe,则将路径包装到 exe并""添加 "%1"看起来像:"c:\testing\test.exe" "%1"

在此处输入图像描述

  1. 要测试它是否有效,请转到Internet Explorer(not Chromeor Firefox) 并输入testus:have_you_seen_this_man这应该会触发您的.exe(给您一些您想要执行此操作的提示 - 说是) 并传递给 args testus://have_you_seen_this_man

这是要测试的示例控制台应用程序:

using System;

namespace Testing
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args!= null && args.Length > 0)
            Console.WriteLine(args[0]);
            Console.ReadKey();
        }
    }
}

希望这可以节省您一些时间。

于 2016-07-05T14:26:20.947 回答
22

MSDN 链接很好,但那里的安全信息不完整。处理程序注册应包含“%1”,而不是 %1。这是一种安全措施,因为某些 URL 源在调用您的自定义协议处理程序之前会错误地解码 %20。

PS。您将获得整个 URL,而不仅仅是 URL 参数。但是除了已经提到的 %20->space 转换之外,URL 可能会受到一些虐待。在您的 URL 语法设计中保持保守会有所帮助。不要随意乱扔 // 否则你会陷入 file:// 的混乱。

于 2008-09-17T10:48:55.600 回答
2

为此目的有一个 npm 模块。

链接:https ://www.npmjs.com/package/protocol-registry

因此,要在 nodejs 中执行此操作,您只需要运行以下代码:

首先安装它

npm i protocol-registry

然后使用下面的代码注册你的入口文件。

const path = require('path');

const ProtocolRegistry = require('protocol-registry');

console.log('Registering...');
// Registers the Protocol
ProtocolRegistry.register({
    protocol: 'testproto', // sets protocol for your command , testproto://**
    command: `node ${path.join(__dirname, './index.js')} $_URL_`, // $_URL_ will the replaces by the url used to initiate it
    override: true, // Use this with caution as it will destroy all previous Registrations on this protocol
    terminal: true, // Use this to run your command inside a terminal
    script: false
}).then(async () => {
    console.log('Successfully registered');
});

然后假设有人打开 testproto://test 然后将启动一个新终端执行:

node yourapp/index.js testproto://test

它还支持所有其他操作系统。

于 2021-04-30T08:06:12.563 回答