Reputation: 15548
I'd like to write a simple WebExtension that handles certain types of links. I don't want a system wide protocol handler, it should simply work for websites open in my browser.
So for instance when anything causes a magnet:// link to be opened, I'd like to intercept that so that the WebExtension handles it.
And if possible I'd like to prevent system applications from handling it while the WebExtension is enabled.
At first I thought that I could use registerProtocolHandler:
navigator.registerProtocolHandler("magnet", "*%s", "Magnet handler");
But I don't think that this would do what I want it to...
My next idea was to use a click event on all a-elements:
document.getElementsByTagName('a').addEventListener('click', event => {
let link = event.target.href
if (link.startsWith('magnet://')) {
// handle magnet link
return false
}
}
But that would only work for links that were clicked on. A link that is opened using JavaScript would not be affected, so that wouldn't work either..
Upvotes: 3
Views: 597
Reputation: 432
I used a trick in an extension to do just that: Register your protocol handler in the manifest:
"protocol_handlers": [
{
"protocol": "magnet",
"name": "Torrent Control Reloaded Magnet Handler",
"uriTemplate": "https://torrent-control-reloaded.invalid/%s"
}
]
then handle the request as you wish:
browser.webRequest.onBeforeRequest.addListener(
(details) => {
var parser = document.createElement('a');
parser.href = details.url;
var magnetUri = decodeURIComponent(parser.pathname).substr(1);
// do what you want with magnetUri
return {cancel: true}
},
{urls: ['https://torrent-control-reloaded.invalid/*']},
['blocking']
);
It's not nice, but it works. You can find the extension here: https://github.com/Mika-/torrent-control/
Upvotes: 2
Reputation: 1343
Work is underway here to support custom protocol handlers: https://bugzilla.mozilla.org/show_bug.cgi?id=1271553
Upvotes: 1