Insert a Script into a iFrame's Header, withou

2020-04-15 06:12发布

问题:

I'm looking to add a script to an iFrame's header while not losing everything contained in the iFrame's body or header...

here is what I have right now which does update the iFrame with the new script, but it cleans everything in the iframe out, not appends which is what I'd like. thxs! B

    // Find the iFrame
    var iframe = document.getElementById('hi-world');

    // create a string to use as a new document object
    var val = '<scr' + 'ipt type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></scr' + 'ipt>';

    // get a handle on the <iframe>d document (in a cross-browser way)
    var doc = iframe.contentWindow || iframe.contentDocument;
    if (doc.document) { doc = doc.document;}

    // open, write content to, and close the document
    doc.open();
    doc.write(val);
    doc.close();

回答1:

var headID = document.getElementsByTagName("head")[0];         

var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'yourpath';
headID.appendChild(newScript);