Home > other >  How to add JavaScript to newly created document with DOMImplementation.createHTMLDocument()
How to add JavaScript to newly created document with DOMImplementation.createHTMLDocument()

Time:10-18

The following code snippet creates a new DOM document with a button inside it and adds it to an iframe. I want to add a JavaScript code inside the new DOM document so that when I click the button id dose something like alert.

I tried the following code but it doesn't work.

<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>

CodePudding user response:

You really don't need to create a new document.

Just get a reference to the document within the frame and do everything within that context.

    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);
        }

    }

Plunker demo

  • Related