Registering a custom protocol ha

2018-07-17  本文已影响13人  许一沐

Chrome 13 finally includes navigator.registerProtocolHandler. This API allows web apps to register themselves as possible handlers for particular protocols. For example, users could select your application to handle "mailto" links.

Register a protocol scheme like:

<pre class="prettyprint notranslate" translate="no" style="box-sizing: inherit; background: rgb(247, 247, 247); color: rgb(55, 71, 79); font: 400 14px/20px "Roboto Mono", monospace; padding: 8px; margin: 16px 0px; overflow-x: auto; position: relative; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">navigator.registerProtocolHandler( 'web+mystuff', 'http://example.com/rph?q=%s', 'My App'); </pre>

The first parameter is the protocol. The second is the URL pattern of the application that should handle this scheme. The pattern should include a '%s' as a placeholder for data and it must must be on the same origin as the app attempting to register the protocol. Once the user approves access, you can use this link through your app, other sites, etc.:

<pre class="prettyprint notranslate" translate="no" style="box-sizing: inherit; background: rgb(247, 247, 247); color: rgb(55, 71, 79); font: 400 14px/20px "Roboto Mono", monospace; padding: 8px; margin: 16px 0px; overflow-x: auto; position: relative; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><a href="web+mystuff:some+data">Open in "My App"</a> </pre>

Clicking that link makes a GET request to http://example.com/rph?q=web%2Bmystuff%3A:some%20data. Thus, you have to parse q parameter and manually strip out data from the protocol.

It's worth noting that Firefox has had navigator.registerProtocolHandler implemented since FF3. One difference in Chrome's implementation is around custom protocols. Those need to be prefixed with "web+", as seen in the example above. The following protocols do not need a "web+" prefix: "mailto", "mms", "nntp", "rtsp", "webcal".

More information on this API can be found on the MDN article.

https://developers.google.com/web/updates/2011/06/Registering-a-custom-protocol-handler

上一篇下一篇

猜你喜欢

热点阅读