Setting the base tag of a dynamically created ifra

2019-07-21 06:29发布

问题:

I'm trying to dynamically create an iframe and set it's base tag before it is created.

ifrm = document.createElement("IFRAME"); 
ifrm.setAttribute("src", "test.html"); 
ifrm.style.width = 400+"px"; 
ifrm.style.height = 100+"px"; 

//before creating it, can we set he base tag?
//I.E. <base href="http://example.com/MyFolder/" />
var bt = ifrm.contentDocument.createElement("base");
bt.setAttribute("href", "http://www.example.com/Folder/");
ifrm.contentDocument.getElementsByTagName("head")[0].appendChild(bt);

document.body.appendChild(ifrm);

I know i can set the base tag in the iframes src file itself. But I need to set it here. Thanks.

回答1:

You can append a <base> element to ifrm.contentDocument.getElementsByTagName("head").

You'll need to create it in the child document by calling ifrm.contentDocument.createElement("base")

For example:

var bt = ifrm.contentDocument.createElement("base");
bt.setAttribute(...);
ifrm.contentDocument.getElementsByTagName("head")[0].appendChild(bt);