0

Our Firefox addon issues queries to Google at the backend (main.js), then extracts some content through xpath. For this purpose, we use innerHTML to create a document instance for xpath parsing. But when we submit this addon to Mozilla, we got rejected because:

This add-on is creating DOM nodes from HTML strings containing potentially unsanitized data, by assigning to innerHTML, jQuery.html, or through similar means. Aside from being inefficient, this is a major security risk. For more information, see https://developer.mozilla.org/en/XUL_School/DOM_Building_and_HTML_Insertion

Following the link provided, we tried to replace innerHTML with nsIParserUtils.parseFragment(). However, the example code:

let { Cc, Ci } = require("chrome");
function parseHTML(doc, html, allowStyle, baseURI, isXML) {
  let PARSER_UTILS = "@mozilla.org/parserutils;1";
  ...

The Cc, Ci utilities can only be used on main.js, while the function requires a document (doc) as the argument. But we could not find any examples about creating a document inside main.js, where we could not use document.implementation.createHTMLDocument("");. Because main.js is a background script, which does not have reference to the global built-in document.

I googled a lot, but still could not find any solutions. Could anybody kindly help?

Joy
  • 9,430
  • 11
  • 44
  • 95
  • 1
    Your main script has access to multiple `` elements. Which you pick would largely depend on the namespace you want that document to exist in (XUL or HTML, with other possibilities), or the purpose for which you need the ``. A side issue is that there is no "global" built in ``; there are lots of `` elements (more than at least one per tab + others). [This answer](http://stackoverflow.com/a/29228418/3773011) has code which will get a reference to *a* `` and *a* `` for the current browser window. – Makyen Dec 09 '16 at 22:37

1 Answers1

1

You probably want to use nsIDOMParser instead, which is the same as the standard DOMParser accessible in window globals except that you can use it from privileged contexts without a window object.

Although that gives you a whole document with synthesized <html> and <body> elements if you don't provide your own. If you absolutely need a fragment you can use the html5 template element to extract a fragment via domparser:

let partialHTML = "foo <b>baz</b> bar"
let frag = parser.parseFromString(`<template>${partialHTML}</template>`, 'text/html').querySelector("template").content
the8472
  • 40,999
  • 5
  • 70
  • 122