首页 > 解决方案 > 使用 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"> &times; </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。

有什么想法吗?

标签: javascriptxmlgoogle-chrome-extensioninnerhtml

解决方案


推荐阅读