Home > Mobile >  Injecting Jquery to an iframe
Injecting Jquery to an iframe

Time:05-05

From a php page running on our local web server I'm opening one of our web applications in an iframe. Both the pages are hosted on the same server, so I've no cross domain issues.

Editing the page directly isn't an option, so I'm trying to inject jquery-min.js and test.js page into the page loaded in the iframe.

I'm using the following code when the iframe has loaded. I've confirmed the css file is added correctly as this changes the loaded pages background within the iframe, but jquery-min.js and test.js don't appear to do anything.

iframe = iframeModal.body.firstChild.contentWindow.document
    
    var cssLink = document.createElement("link") 
    cssLink.href = protocol   ip   "test.css"; 
    cssLink .rel = "stylesheet"; 
    cssLink .type = "text/css"; 
    iframe.body.appendChild(cssLink);
    
    var jqLink = document.createElement("link") 
    jqLink.href = protocol   ip   "jquery-min.js"; 
    jqLink .type = "text/javascript"; 
    iframe.body.appendChild(jqLink);
    
    var jqtest = document.createElement("link") 
    jqtest.href = protocol   ip   "test.js"; 
    jqtest .type = "text/javascript"; 
    iframe.body.appendChild(jqtest);

test.js contains:

$(document).ready(function() {
    alert ( 'Alert Test' )
})

Can someone advise how I can add jquery-min.js and test.js correctly to the loaded iframe page so I can run jquery in the iframe page.

Thanks

CodePudding user response:

var jqLink = document.createElement("link") 
jqLink.href = protocol   ip   "jquery-min.js"; 

Script resources are not embedded using link elements, but script.

(And with script you need to set the src attribute then, instead of href.)

  • Related