CreateContextualFragment在safari中不起作用

CreateContextualFragment not working in safari

本文关键字:不起作用 safari CreateContextualFragment      更新时间:2023-12-28

我们在safari中的函数(createContextualFragment)有问题。

我们需要在正文中添加一些内容,所以我们使用这行代码。

代码:

document.getElementsByTagName('body')[0].insertBefore(document.createRange().createContextualFragment("<div></div><script src="LINK_SOURCE"></script>"), null);

这行代码在Chrome和Firefox上运行良好,但我们在Safari中的createContextualFragment遇到了一些问题。

Safari中的错误:

createContextualFragment--asyncronousDocumentWrite2.html:28:115NotSupportedError:DOM异常9:实现不支持请求的对象类型或活动

我意识到我的答案来得有点晚,但我最近遇到了类似的情况。

我发现了什么

根据https://developer.mozilla.org/en-US/docs/Web/API/Range/createContextualFragment#Browser_compatibilitySafari 9.0或9.1不支持Range.createContextualFragment()。不过,它在Safari 10中运行良好。

你能做什么

由于Safari不支持createContextualFragment,我们可以将创建文档片段的责任委托给jQuery。以下说明了根据您使用的jQuery版本来执行此操作的两个选项:

  1. jQuery 1.8或更新版本使用ParseHTML
    document.getElementsByTagName('body')[0].insertBefore($.parseHTML("<div></div><script src='http://google.ca'></script>"), null);

  2. 否则让jQuery来决定该怎么做
    document.getElementsByTagName('body')[0].insertBefore($("<div></div> <script src='http://google.ca'></script>"), null);

我发现设置range.selectNodeContents(document.createElement('div'));可以修复本文间接指出的问题https://grrr.tech/posts/create-dom-node-from-html-string/#range.
我的示例用法:

document.querySelectorAll('.container').forEach((el) => {
  const range = document.createRange();
  range.selectNodeContents(el);
  range.deleteContents();
  range.selectNodeContents(document.createElement('div')); // fix for safari
  el.appendChild(range.createContextualFragment(htmlContent));
});