Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically created editable iframe not working in Firefox

I have an iframe that is generated in JavaScript with createElement() when a function is fired, which becomes a text editor. It works just fine in Chrome, Safari and Edge, but in Firefox, the innerHTML text, "Text Layer", will briefly flash within the iframe and then it disappears and the iframe doesn't seem to be editable. Upon inspection, the iframe's body tag is empty. If I set contentEditable to true on the iframe's body tag in the inspector it seems to work properly, but when I try to set this in my JS function, nothing happens in Firefox.

I'm guessing this has something to do with the iframe being created in JavaScript, since setting the designMode of an iframe already in the DOM to 'On' with JS seems to work properly. Wondering if there's a way to get this to work in Firefox, maybe another method of creating the iframe? I have seen some similar problems that were solved by putting some javascript in the iframe's src, as in the comments here, but that apparently causes problems in other browsers. Creating the iframe in JS is preferable to appending it from somewhere.

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();
};
like image 661
user2489793 Avatar asked Oct 09 '18 03:10

user2489793


Video Answer


1 Answers

Found this 15 year old bug report and was able to get it work by setting the contentWindow properties inside of a setTimeout function.

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();
};
like image 193
user2489793 Avatar answered Sep 28 '22 02:09

user2489793