user429620
user429620

Reputation:

Chrome Extension : Custom Protocol?

Are there methods to register a custom protocol with a google chrome extension like you can in firefox :

const kSIMPLEURI_CONTRACTID = "@mozilla.org/network/simple-uri;1"; 
const kIOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1"; 
const nsISupports = Components.interfaces.nsISupports; 
const nsIIOService = Components.interfaces.nsIIOService; 
const nsIProtocolHandler = Components.interfaces.nsIProtocolHandler; 
const nsIURI = Components.interfaces.nsIURI; 

I want the protocol:

xyz:

Not xyz://

Is this possible?

Upvotes: 6

Views: 8271

Answers (2)

Mohamed Mansour
Mohamed Mansour

Reputation: 40169

The new way would be using declarativeNetRequest

Create a rule rules.json that does a redirect.

[
  {
    "id": 1,
    "priority": 1,
    "action": {
      "type": "redirect",
      "redirect": { 
        "regexSubstitution": "chrome-extension://xxxxxxxxxxxxxxxx/redirect.html#\\1"
      }
    },
    "condition": { 
      "regexFilter": "^https://mohamedmansour.com/join/([\\w]+)", 
      "resourceTypes": ["main_frame"]
    }
  }
]

Then within your redirect.html script, handle it, you can use chrome.runtime.sendMessage to act upon it.

function closeCurrentTab() {
  chrome.tabs.getCurrent(tab => chrome.tabs.remove(tab.id, () => {}))
}

if (location.hash)
  chrome.runtime.sendMessage({ command: 'AppLink', data: location.hash }, () => closeCurrentTab())
else
  closeCurrentTab()

That is how you can do App Deep Linking within Extensions with a fake URL link.

Upvotes: 0

Rob W
Rob W

Reputation: 349042

Chrome does not offer a way to set custom handlers for the xyz: scheme.

There are some ways to emulate the behavior though:

  • Use Content scripts to set up an event listener for clicks on links which point to xyz:....
  • Use the webRequest API to intercept and redirect all requests from the default search provider to a custom URL. I'm using this method for catching wildcard search keywords, but it can also be used for supporting fake schemes. Unfortunately, the extension would be quite specific to the user's search settings, because it would do something like this:

    Redirect http://google.com/search?q=xyz%3Awhatever
          to chrome-extension://.../whatever
    

in both cases, you won't see xyz:whatever in the omnibox, though.

navigator.registerProtocolHandler should be the best way to register a xyz: handler. Unfortunately, it is quite limited at the moment. Custom protocols must be prefixed with web+. Also take a look at the list of open bugs for this API.

Upvotes: 6

Related Questions