javascript - 使用 XML 页面时避免 [Uncaught DOMException: Failed to set the 'innerHTML' property on 'Element'] 的条件
问题描述
我正在开发一个 chrome 扩展项目,其中我有一个通过“innerHTML”将 div 注入当前页面的功能。这在 HTML 页面上工作正常,但是当页面是 XML 类型(例如 VAST XML 类型)时,我收到以下错误:
Uncaught DOMException: Failed to set the 'innerHTML' property on 'Element': The provided markup is invalid XML, and therefore cannot be inserted into an XML document.
我的代码如下:
function injectContextMenuContainer() {
toolboxElement = document.createElement('div')
toolboxElement.setAttribute('id', 'contextMenu-data-root') // root div
// toolboxElement.setAttribute('class', 'close');
document.body.appendChild(toolboxElement)
// creates div unde root div
toolboxElement.innerHTML = `
<button id="closeButton"> × </button>
<div id="contextMenu-data-container"></div>
`
// Assign listener to variable and add onclick function to close div
const closeButton = document.getElementById('closeButton')
closeButton.onclick = handleClose
}
function handleClose() {
const containerElement = document.getElementById('contextMenu-data-root')
containerElement.style.display = 'none'
}
injectContextMenuContainer()
我要做的是在调用函数的地方添加一个条件,所以我只能在页面是 HTML 类型时执行这个函数,否则不执行。
我在寻找实现这一目标的正确方法时遇到了一些问题。最终目标是当页面是一个巨大的 XML 类型时函数不执行。在这种情况下,innerHTML 不起作用,因为 XML 页面不是 HTML。
有什么想法吗?
解决方案
推荐阅读
- c++ - 接受字符串输入而不显示其实际内容(对于 PASSWORDS)
- r - 图例没有出现在ggplot中
- python - 在 0 和 1 之间缩放数据,并将它们的分布转换为正态分布会改变模型的 RMSLE
- apache-kafka - 用于不同值的 KSQL
- javascript - Laravel 编辑更新 JSON 数组并使用 JavaScript 删除特定输入
- javascript - 更新滚动反应钩子上的状态
- c# - 使用 Newtonsoft Json.Net 反序列化字符串化(引号括起来)嵌套对象
- c++ - 向量元素的移动分配不起作用,而是调用复制分配
- html - HTML 文件不会连接到 CSS
- build - 在 Azure DevOps 中将一个存储库构建到另一个存储库