Use registerProtocolHandler without contentWindow

核能气质少年 提交于 2019-12-02 08:32:26

You simply cannot use that high-level API without a window (and you probably don't want to use it anyway, because it will not actually add the handler, but show a UI notification that first asks the user to add it; which is not only not what you want, but also won't work because there is no UI to display that notification in the first place).

Instead, you'll want to create your own version based on the implementation that omits all those security checks, UI notifications, etc.

Based on registerNotificiation, it would look something like this.

var protocolScheme = "mailtoorsomething";
var uri = Services.io.newURI("someuri?with_%s_replacement", null, null);
var name = "Some Name";
var desc = "Some description";

var protocolHandler = Services.io.getProtocolHandler(protocolScheme);
if (!(protocolHandler instanceof Ci.nsIExternalProtocolHandler)) {
  throw new Error("Cannot register handler for built-in protocol");
}

var eps = Cc["@mozilla.org/uriloader/external-protocol-service;1"].
          getService(Ci.nsIExternalProtocolService);
var handlerInfo = eps.getProtocolHandlerInfo(protocolScheme);
var handlers =  handlerInfo.possibleApplicationHandlers;
for (let i = 0; i < handlers.length; i++) {
  let h = handlers.queryElementAt(i, Ci.nsIWebHandlerApp);
  if (h.uriTemplate == uri.spec) {
    throw new Error("Already registered");
  }
}

var handler = Cc["@mozilla.org/uriloader/web-handler-app;1"].
              createInstance(Ci.nsIWebHandlerApp);
handler.name = name;
handler.detailedDescription = desc;
handler.uriTemplate = uri.spec;
handlerInfo.possibleApplicationHandlers.appendElement(handler, false);

handlerInfo.alwaysAskBeforeHandling = false;
handlerInfo.preferredApplicationHandler = handler;
handlerInfo.preferredAction = Ci.nsIHandlerInfo.useHelperApp;

var hs = Cc["@mozilla.org/uriloader/handler-service;1"].
          getService(Ci.nsIHandlerService);
hs.store(handlerInfo);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!