El siguiente fragmento de código crea un nuevo documento DOM con un button dentro y lo agrega a un iframe . Quiero agregar un código JavaScript dentro del nuevo documento DOM para que cuando haga clic en el button identifique algo como alerta.
Probé el siguiente código pero no funciona.
<html> <head> </head> <body> <p><button id="btn" >Click Here</button> to create a new document and insert it below.</p> <iframe id="theFrame" src="about:blank"></iframe> <script type="text/javascript"> document.getElementById("btn").onclick = function () { var frame = document.getElementById("theFrame"); var doc = document.implementation.createHTMLDocument("New Document"); var button = doc.createElement("button"); button.innerHTML = "Alert"; button.setAttribute("id","btn1"); var script = doc.createElement("script"); script.innerHTML = "document.getElementById('btn1').onclick = function() {alert('button clicked!')};"; try { doc.body.appendChild(button); } catch(e) { console.log(e); } try { doc.body.appendChild(script); } catch(e) { console.log(e); } // Copy the new HTML document into the frame var destDocument = frame.contentDocument; var srcNode = doc.documentElement; var newNode = destDocument.importNode(srcNode, true); destDocument.replaceChild(newNode, destDocument.documentElement); } </script> </body>Realmente no necesita crear un nuevo documento.
Simplemente obtenga una referencia al documento dentro del marco y haga todo dentro de ese contexto.
document.getElementById("btn").onclick = function () { var frame = document.getElementById("theFrame"); // reference to the iframe document instead of createHTMLDocument var doc = frame.contentDocument var button = doc.createElement("button"); button.innerHTML = "Alert"; button.setAttribute("id","btn1"); var script = doc.createElement("script"); script.innerHTML = "document.getElementById('btn1').onclick = function() {alert('button clicked!')};"; try { doc.body.appendChild(button); } catch(e) { console.log(e); } try { doc.body.appendChild(script); } catch(e) { console.log(e); } }