动态创建的可编辑 iframe 在 Firefox 中不起作用

Dynamically created editable iframe not working in Firefox

我有一个 iframe,它在 JavaScript 和 createElement() 中生成,当一个函数被触发时,它变成了一个文本编辑器。它在 Chrome、Safari 和 Edge 中工作得很好,但在 Firefox 中,innerHTML 文本 "Text Layer" 会在 iframe 中短暂闪烁,然后消失,iframe 似乎没有可编辑。经检查,iframe 的 body 标签是空的。如果我在检查器中将 iframe 的 body 标签设置为 true,它似乎工作正常,但是当我尝试在我的 JS 函数中设置它时,Firefox 中没有任何反应。

我猜这与在 JavaScript 中创建的 iframe 有关,因为将 DOM 中已有的 iframe 的 designMode 设置为 'On' 与 JS 似乎工作正常。想知道是否有办法让它在 Firefox 中工作,也许是另一种创建 iframe 的方法?我已经看到一些类似的问题,通过在 iframe 的 src 中放置一些 javascript 来解决,如评论 here 中所述,但这显然会导致其他浏览器出现问题。在 JS 中创建 iframe 比从某处附加它更可取。

function text() {
var rtf = document.createElement("iframe");
rtf.name = "richTextField";
rtf.id = "richTextField";
rtf.className = "texteditor";
var dwrap = document.createElement("div");
dwrap.appendChild(rtf);
var tframe = document.getElementById("richTextField");
tframe.contentWindow.document.designMode = 'On';
tframe.contentWindow.document.body.innerHTML = "Text Layer";
tframe.contentWindow.document.getElementsByTagName('body')[0].focus();
tframe.onload = autosize();
};

找到这个 15 year old bug report 并且能够通过在 setTimeout 函数中设置 contentWindow 属性来使其工作。

function text() {
var rtf = document.createElement("iframe");
rtf.name = "richTextField";
rtf.id = "richTextField";
rtf.className = "texteditor";
var dwrap = document.createElement("div");
dwrap.appendChild(rtf);
var tframe = document.getElementById("richTextField");

setTimeout(function(){ 
tframe.contentWindow.document.designMode = 'On';
tframe.contentWindow.document.body.innerHTML = "Text Layer";
tframe.contentWindow.document.getElementsByTagName('body')[0].focus();
}, 0);

tframe.onload = autosize();
};