Search code examples
javascriptframesuserscriptsframeset

How to add frames to an existing frameset using userscript?


The target page has a simple HTML setup:

<html>
<body>
    <frameset id="mainset" rows="50%,50%">
    ...
    </frameset>
</body>
</html>

and I'd like to add frames using JavaScript.


This doesn't work:

var parent = document.getElementsByTagName("frameset")[0];
var child = document.createElement("frame");
child.src = "about:blank";
child.style = "background-color: red;";

parent.appendChild(child);

This does work, but it creates an iframe:

var parent = document.getElementsByTagName("body")[0];
var child = document.createElement("iframe");
child.src = "about:blank";
child.style = "background-color: red;";

parent.appendChild(child);

Is there a way to add frames to the frameset using javascript?

Sorry if this question has been asked before. I searched and found a lot of 'solutions' for people having similar problems, but those don't seem to apply here.

The target page looks like this:

screenshot


Solution

  • It's not enough to add a new <frame>. You must also adjust the rows or cols attribute of the containing <frameset>.

    Also, if the frameset has an id, use it instead of trying to get the node by tagname. (Ids are fast and unique.)

    Code like this will work (for now):

    You can see the code in action at this jsBin.

    var parent      = document.getElementById ("mainset");
    var child       = document.createElement ("frame");
    child.style     = "background-color: pink;";
    
    parent.appendChild (child);
    parent.rows     = "30%,30%,30%"
    
    var docRdyInt   = null;
    var frmCW       = child.contentWindow;
    if (frmCW) {
        //-- Must wait for the new frame to be writable, esp in Firefox.
        docRdyInt   = setInterval (createFramedPage, 50);
    }
    else {
        alert ("Oopsie! may be a rendering delay in some cases. Try code from console.");
    }
    
    function createFramedPage () {
        if (frmCW.document.readyState == "complete") {
            clearInterval (docRdyInt);
            frmCW.document.body.innerHTML = '<p>Hello World!</p>';
        }
    }