如何为 Firefox 插件使用 `nsIParserUtils.parseFragment()`
How to use `nsIParserUtils.parseFragment()` for Firefox addon
我们的 Firefox 插件在后端 (main.js
) 向 Google 发出查询,然后通过 xpath 提取一些内容。为此,我们使用 innerHTML
创建一个 document
实例用于 xpath 解析。但是当我们将这个插件提交给 Mozilla 时,我们被拒绝了,因为:
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
根据提供的 link,我们尝试将 innerHTML
替换为 nsIParserUtils.parseFragment()
。但是,示例代码:
let { Cc, Ci } = require("chrome");
function parseHTML(doc, html, allowStyle, baseURI, isXML) {
let PARSER_UTILS = "@mozilla.org/parserutils;1";
...
Cc, Ci
实用程序只能在 main.js
上使用,而该函数需要 document
(doc
) 作为参数。 但是我们找不到任何关于在 main.js
中创建 document
的示例,我们无法在其中使用 document.implementation.createHTMLDocument("");
。因为main.js
是后台脚本,没有引用全局内置的document
.
我用谷歌搜索了很多,但仍然找不到任何解决方案。有人可以帮忙吗?
您可能想使用 nsIDOMParser instead, which is the same as the standard DOMParser 可在 window 全局变量中访问,除非您可以在没有 window 对象的情况下从特权上下文中使用它。
尽管如果您不提供自己的元素,这会为您提供包含合成 <html>
和 <body>
元素的整个文档。如果你绝对需要一个片段,你可以使用 html5 模板元素通过 domparser 提取片段:
let partialHTML = "foo <b>baz</b> bar"
let frag = parser.parseFromString(`<template>${partialHTML}</template>`, 'text/html').querySelector("template").content
我们的 Firefox 插件在后端 (main.js
) 向 Google 发出查询,然后通过 xpath 提取一些内容。为此,我们使用 innerHTML
创建一个 document
实例用于 xpath 解析。但是当我们将这个插件提交给 Mozilla 时,我们被拒绝了,因为:
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
根据提供的 link,我们尝试将 innerHTML
替换为 nsIParserUtils.parseFragment()
。但是,示例代码:
let { Cc, Ci } = require("chrome");
function parseHTML(doc, html, allowStyle, baseURI, isXML) {
let PARSER_UTILS = "@mozilla.org/parserutils;1";
...
Cc, Ci
实用程序只能在 main.js
上使用,而该函数需要 document
(doc
) 作为参数。 但是我们找不到任何关于在 main.js
中创建 document
的示例,我们无法在其中使用 document.implementation.createHTMLDocument("");
。因为main.js
是后台脚本,没有引用全局内置的document
.
我用谷歌搜索了很多,但仍然找不到任何解决方案。有人可以帮忙吗?
您可能想使用 nsIDOMParser instead, which is the same as the standard DOMParser 可在 window 全局变量中访问,除非您可以在没有 window 对象的情况下从特权上下文中使用它。
尽管如果您不提供自己的元素,这会为您提供包含合成 <html>
和 <body>
元素的整个文档。如果你绝对需要一个片段,你可以使用 html5 模板元素通过 domparser 提取片段:
let partialHTML = "foo <b>baz</b> bar"
let frag = parser.parseFromString(`<template>${partialHTML}</template>`, 'text/html').querySelector("template").content