Здравствуйте делаю добавление картинки с ссылкой. При нажатии на кнопку срабатывает функция insertImg. Дальше картинка появляется и тут же исчезает но чаще всего она вообще не появляется. В чем может быть проблема и как исправить?
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>
<body>
<input type='button' class='btn-block' data-command='Bold' value='B'/><input type='button' class='btn-block' data-command='Italic' value='I'/>
<button type="button" class="btn-block" data-command="image" title="Картинка">Картинка</button>
<br />
<iframe scrolling='no' frameborder='no' src='#' id='frameId' name='frameId' width="800" height="400"></iframe>
<form name="myform" action="#" method="post" onsubmit="return save()">
<p>
<input type="hidden" id="content" name="content" value="" />
</p>
<script type="text/javascript">
let edit1;
let doc;
function init()
{
var isGecko = navigator.userAgent.toLowerCase().indexOf("gecko") != -1;
console.log(isGecko);
var iframe = document.getElementById("frameId");
edit1 = iframe.contentWindow;
doc = iframe.contentDocument;
iHTML = "<html><head>";
iHTML += "</head><body><span class=\"marker\" style=\"display: none; line-height: 0;\"></span></body></html>";
doc.open();
doc.write(iHTML);
doc.close();
doc.designMode = "on";
doc.body.contentEditable = true;
$('.btn-block').on("click", function(e) {
e.preventDefault();
e.stopPropagation();
let target = e.target;
tag = target.firstChild;
let myclass = "";
if (target.getAttribute("data-command") === "Bold") {
edit1.focus();
edit1.document.execCommand("bold", null, "");
}
if(target.getAttribute("data-command") === "image") {
// alert(target.getAttribute("data-command"));
insertImg();
}
if (target.getAttribute("data-command") === "Italic") {
edit1.focus();
edit1.document.execCommand("italic", null, "");
}
});
function insertImg()
{
var img=new Image();
img.onload=function()
{
var rangeElement = document.createElement("a");
rangeElement.href = "https://i.ytimg.com/vi/ORxm0hkVuo8/hqdefault.jpg";
j = $('iframe, body').contents().find("span.marker");
rangeElement.appendChild(img);
j.replaceWith(rangeElement);
}
img.src="https://i.ytimg.com/vi/ORxm0hkVuo8/hqdefault.jpg";
}
function addBlock(myclass)
{
}
}
init();
//});
</script>
<p>
<input type="submit" value="Отправить" />
</p>
</form>
</body>