Unable to inject jquery in iframe - javascript

i'm having issues with injecting jQuery into an iframe. With regular javascript it works as intended, but not with jQuery.
I have appended the jQuery CDN link to the iframes <head> and if I inspect the iframe element i can see it there. I can also see the scripts in the body tag after the function has run.
When executing the jquery script i get this error.
Uncaught ReferenceError: $ is not defined
If i add these I don't get the error but nothing happens.
$iframe[0].contentWindow.$ = $;
$iframe[0].contentWindow.jQuery = $;
I've tried to add timeouts to the append function to see if it was an issue with the CDN not loading quick enough. But no difference.
If i put the HTML and jQuery outside the iframe everything works as intended so I think there is something i've done wrong or missed regarding the iframe. Anyone have an idea what I could've done wrong here?
This is the function that injects the scripts
injectScript() {
let $iframe = $('#iframe');
$iframe.ready(function () {
$iframe[0].contentWindow.$ = $;
$iframe[0].contentWindow.jQuery = $;
const jqueryScript = document.createElement("script");
jqueryScript.type = "text/javascript";
jqueryScript.src = "https://code.jquery.com/jquery-3.5.1.min.js"
$iframe.contents().find("head").append(jqueryScript);
// This code works
let vanilla = "<script>document.getElementById('vanilla').innerHTML = 'bar'<";
vanilla += "/script>";
$iframe.contents().find("body").append(vanilla);
// This code works **not**
let jQuery = "<script>$('#jquery').text('foo')<";
jQuery += "/script>";
$iframe.contents().find("body").append(jQuery);
})
}
the html in the iframe
<div id="jquery">foo</div>
<div id="vanilla">foo</div>

Related

Error when loading Jquery 2.1.4 file

I have a little issue bugging me for several hours now, so i come to see you guys for some help.
Here is the situation :
I use jquery-2.1.4.js in my application. If i test my fragment of code outside the application it work correctly but when it is in my application Jquery doesn't load correctly.
Jquery is include correctly in my repository and called in my page before the end of the body tag like this (i moved it away from the head tag thiking it might be the issue but i still got the same error) :
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
I test if Jquery is correctly loaded like this :
if (typeof jQuery == 'undefined') {
// jQuery is not loaded
alert("jquery not loaded,force it");
var jq = document.createElement('script');
jq.type = 'text/javascript';
// Path to jquery.js file, eg. Google hosted version
jq.src = 'js/jquery-2.1.4.js';
document.getElementsByTagName('head')[0].appendChild(jq);
} else {
// jQuery is loaded
alert("jquery is loaded");
}
The issue is here now :), everytime I end up in the not loaded part, and when I force Jquery load, I got an error line 3539 of the Jquery file on the function :
function Data() {
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Data.uid++;
}
With the error message :
This object does not have this property or method : defineProperty
(not sure about the English for this one, my error message is in French).
Just so you know, there is no action done on Load, only when i click a button. Our file with JS codes are in a .include, so i don't know if this is why the error is trigger or not.
Anyway, thanks for taking the time to help me.
Slayner.
You need to include the expando library, since it is not part of standard jQuery. Try adding this:
<script src="//cdn.rawgit.com/cantino/expando/38affee59bffdd87975c492472362c69ce0f6fda/jquery.expando.js"></script>
Right after this:
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
Okay, so the reason why this did not work for me was that our application is loaded as an IE5 application and is not compatible with JQuery (well not a version from these last few year.)

Cloning javascript tags from parent page into child page

I'm using window.open to create an empty window and then populating it using jquery DOM manipulation methods. One thing I'd like to do is make sure the new window has all the same scripts available in it that are in the parent window. I'm also duplicating all the style sheets, plus any other data that's in the parent window HEAD section, so what I decided to do is this:
$(floatingMap.window.document.head).append(
$("<base>", {"href": location.href})).append(
$("head").children().clone()));
This first creates a <base> tag that ensures the relative URLs in the source document are interpreted correctly, then injects a copy of all the tags from the head section of the source document. I can inspect the injected objects in the new window using Chrome's DOM inspector, and everything looks OK, but the problem I'm having is that the scripts aren't loading. The stylesheets, on the other hand, are loading fine. Any ideas what I can do to make the scripts load correctly?
Update:
In a potentially related problem, I've found that the following code has unexpected results:
$(floatingMap.window.document.head).append(
$("<script>").text("window.opener.childWindowReady()"));
This causes the specified code to execute in the context of the parent window, not the child window. Any ideas why this would be the case?
This appears to be a jquery bug. Excluding the script tags from the jquery operation and then adding those using pure javascript works as expected:
var scripts = document.getElementsByTagName("script");
function loadScript (index)
{
if (index == scripts.length)
onChildWindowReady ();
else if (scripts[index].src)
{
console.log ("injecting: " + scripts[index].src);
var inject = document.createElement("script");
inject.src = scripts[index].src;
floatingMap.window.document.head.appendChild(inject);
inject.onload = function () { loadScript (index + 1); };
}
else
loadScript (index + 1);
}
loadScript (0);
In addition with document.writeln it is possible to add all contents dynamically and also execute them.
For example,
jQuery(document).ready(function(){
jQuery('body').append("jquery loaded");
var w = window.open();
var htmlContent = document.documentElement;
w.document.writeln("<html>"+htmlContent.innerHTML+"</html>");
w.document.close();
});
This demostrates opening a clone of the jsfiddle result window that will include jquery as well as script content within head.
http://jsfiddle.net/6Qks8/

How to dynamically insert jquery code

I am trying use jQuery's rich animation features on dynamically loaded content.
I can dynamically insert script into an element like so:
var element = document.createElement("div");
element.innerHTML = "some html here";
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'alert("Alert!");';
element.appendChild (script);
The problem occurs when I try to insert jquery code into the script element. This does not work and causes the script to not run at all.
var element = document.createElement("div");
element.innerHTML = "some html here";
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'alert("Alert!");\n';
script.text = script.text+'$("div").animate({height:300,opacity:0.4},"slow");\n';
element.appendChild (script);
I can successfully append javascript code to change the elements I want, but using jquery functions will simplify things.
With firebug I can see the script elements has been loaded into the dom, however when I add the jquery code to it, nothing happens, not even the alert.
I have included the jquery source file in my main document and wrapped all of my code into a window.addEventListener('load', function()) to call the functions that initiates the code above when the page finishes loading.
Is there a way to dynamically create calls to jquery functions? Am I going about this the right way? I've been stumped for a while and google hasnt solved this one for me, any help is appreciated.
This should do what you want:
$('body').append('<s' + 'cript>console.log("lol");</script>');
But why are you not wrapping your code into a function which you can then call whenever you please?
function iAnimateThings() {
$("div").animate({height:300,opacity:0.4},"slow");
}
hey nothing wrong with your code you just missed one single inverted comma on this line
script.text = script.text+'$("div").animate({height:300,opacity:0.4},"slow")';
here is your working fiddle
http://jsfiddle.net/vYut9/

Loading JQuery with Javascript from footer

If you would like to get to the point, here is my question:
Is there any way to call a specific script to load first in javascript?
For more detail, please read below:
I have a javascript file that is loading from the bottom of my HTML <body>. Unfortunately, there is no JQuery in the head, so I have to add it through this javascript file.
What I need to do is add a JQuery lightbox plugin.
My problem is that when I load the page, sometimes JQuery isn't the first thing loaded. So I receive the error "jQuery is not defined". Which will then raise more errors for undefined methods from the plugin.
This doesn't happen all the time, only sometimes. Which makes me think it's a loading/order of operations issue.
Is there any way I can guarantee that my JQuery script is the first thing loaded?
Here is some of my javascript file.
//Get head element
var head = document.getElementsByTagName("head")[0];
//Create and insert JQuery
var jquery = document.createElement('script');
jquery.type = 'text/javascript';
jquery.src = 'http://image.iloqal.com/lib/fe6b/m/1/jquery.1.7.2.js';
head.insertBefore(jquery,head.childNodes[4]);
function thescripts() {
var fancybox = document.createElement('script');
fancybox.type = 'text/javascript';
fancybox.src = 'http://image.iloqal.com/ilejquery.fancybox-1.3.4.pack.js';
head.appendChild(fancybox);
var thebody = document.getElementsByTagName('body')[0];
thebody.appendChild(thediv);
thediv.appendChild(theimg);
//Run fancybox
thebody.onload = function() {
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
}
};
if(jquery.attachEvent){
jquery.attachEvent("onload",thescripts());
} else {
jquery.onload = thescripts();
}
Any help is appreciated!
Try this. Add this piece of code inside your javascript file which is called from your footer.
<script type="text/javascript">
if(typeof jQuery == 'undefined'){
document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></'+'script>');
}
</script>
This will include jquery if its not loaded. I think this will fix your issue.
Using $(function() {...do your stuff here...}); is the way to go to be sure jQuery is loaded before the script is executed, but you could probably make it harder for yourself and do:
thebody.onload = function() {
RunMyjQuery();
}
function RunMyjQuery() {
if (typeof $ === 'undefined') {
setTimeout(RunMyjQuery, 500);
}else{
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
}
}
You're calling thescripts immediately, although you try not to. Use this:
jquery.onload = thescripts; // notice no parentheses
Also, your thebody.onload strategy will not work. Use $(document).ready instead:
$(document).ready(function{
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
});

How do I inject javascript to a page on IE 8?

Lets suppose that I have the following markup:
<div id="placeHolder"></div>
and I have a JavaScript variable jsVar that contains some markup and some JavaScript.
By using Mootools 1.1 I can inject the JavaScript content into the placeholder like this:
$('placeHolder').setHTML(jsVar);
This works in Firefox, Opera, and even Safari and the resulting markup looks like this:
<div id="placeHolder">
<strong>I was injected</strong>
<script type="text/javascript">
alert("I was injected too!");
</script>
</div>
However, on IE 8 I get the following:
<div id="placeHolder">
<strong>I was injected</strong>
</div>
Is there any way to inject the JavaScript on IE 8 or does it security model forbid me from doing this at all?
I tried Luca Matteis' suggestion of using
document.getElementById("placeHolder").innerHTML = jsVar;
instead of the MooTools code and I get the same result. This is not a MooTools issue.
This MSDN post specifically addresses how to use innerHTML to insert javascript into a page. You are right: IE does consider this a security issue, so requires you to jump through certain hoops to get the script injected... presumably hackers can read this MSDN post as well as we can, so I'm at a loss as to why MS considers this extra layer of indirection "secure", but I digress.
From the MSDN article:
<HTML>
<SCRIPT>
function insertScript(){
var sHTML="<input type=button onclick=" + "go2()" + " value='Click Me'><BR>";
var sScript="<SCRIPT DEFER>";
sScript = sScript + "function go2(){ alert('Hello from inserted script.') }";
sScript = sScript + "</SCRIPT" + ">";
ScriptDiv.innerHTML = sHTML + sScript;
}
</SCRIPT>
<BODY onload="insertScript();">
<DIV ID="ScriptDiv"></DIV>
</BODY>
</HTML>
If at all possible, you may wish to consider using a document.write injected script loading tag to increase security and reduce cross-browser incompatibility. I understand this may not be possible, but it's worth considering.
This is how we did it on our site about a year ago to get it working in IE. Here are the steps:
add the HTML to an orphan DOM element
search the orphan node for script tags (orphan.getElementsByTagName)
get the code from those script nodes (save for later), and then remove them from the orphan
add the html leftover that is in the orphan and add it to the placeholder (placeholder.innerHTML = orphan.innerHTML)
create a script element and add the stored code to it (scriptElem.text = 'alert("my code");')
then add the script element to the DOM (preferably the head), then remove it
function set_html( id, html ) {
// create orphan element set HTML to
var orphNode = document.createElement('div');
orphNode.innerHTML = html;
// get the script nodes, add them into an arrary, and remove them from orphan node
var scriptNodes = orphNode.getElementsByTagName('script');
var scripts = [];
while(scriptNodes.length) {
// push into script array
var node = scriptNodes[0];
scripts.push(node.text);
// then remove it
node.parentNode.removeChild(node);
}
// add html to place holder element (note: we are adding the html before we execute the scripts)
document.getElementById(id).innerHTML = orphNode.innerHTML;
// execute stored scripts
var head = document.getElementsByTagName('head')[0];
while(scripts.length) {
// create script node
var scriptNode = document.createElement('script');
scriptNode.type = 'text/javascript';
scriptNode.text = scripts.shift(); // add the code to the script node
head.appendChild(scriptNode); // add it to the page
head.removeChild(scriptNode); // then remove it
}
}
set_html('ph', 'this is my html. alert("alert");');
I have encountered the same issues with IE8 (and IE7)
The only way I could dynamically inject a script (with an src) is by using a timer:
source = "bla.js";
setTimeout(function () {
// run main code
var s = document.createElement('script');
s.setAttribute('src', source);
document.getElementsByTagName('body')[0].appendChild(s);
}, 50);
If you have inline code you would like to inject, you can drop the timer and use the "text" method for the script element:
s.text = "alert('hello world');";
I know my answer has come pretty late; however, better late than never :-)
I am not sure about MooTools, but have you tried innerHTML ?
document.getElementById("placeHolder").innerHTML
= jsVar;
You may need to eval the contents of the script tag. This would require parsing to find scripts in your jsVar, and eval(whatsBetweenTheScriptTags).
Since IE refuses to insert the content by default you will have to execute it yourself, but you can at least trick IE into doing the parsing for you.
Simply use string.replace() to swap all the <script> tags for <textarea class="myScript" style="display:none">, preserving the content. Then stick the result into an innerHTML of a div.
After this is done, you can use
div.getElementsByTagName("textarea")
to get all the textareas, loop through them and look for your marker class ("myScript" in this case), and either eval(textarea.value) or (new Function(textarea.value))() the ones you care about.
I never tried it, it just came to my mind... Can you try the following:
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = '//javascript code here'; // not sure if it works
// OR
script.innerText = '//javascript code here'; // not sure if it works
// OR
script.src = 'my_javascript_file.js';
document.getElementById('placeholder').appendChild(script);
You can use the same technique (DOM) to insert HTML markup.
I am sorry, perhaps I am missing something here--but with this being a mootools 1.11 question, why don't you use assets.js?
// you can also add a json argument with events, etc.
new Asset.javascript("path-to-script.js", {
onload: function() {
callFuncFromScript();
},
id: "myscript"
});
Isn't one of the reasons why we're using a framework not to have to reinvent the wheel all over again...
as far as the 'other' content is concerned, how do you happen to get it? if through the Request class, it can do what you want nicely by using the options:
{
update: $("targetId"),
evalScripts: true,
evalResponse: false
}
When you say it "works" in those other browsers, do you mean you get the alert popup message, or do you just mean the <script> tag makes it into the DOM tree?
If your goal is the former, realize that the behaviour of injecting html with embedded <script> is very browser-dependent. For example in the latest MooTools I can try:
$(element).set('html', '<strong>Foo</strong><script>alert(3)</script>')
and I do not get the popup, not in IE(7), not in FF(3) (however I do get the <script> node into the DOM successfully). To get it to alert in all browsers, you must do as this answer does.
And my comment is really late, but it's also the most accurate one here - the reason you're not seeing the <script> contents running is because you didn't add the defer attribute to the <script> tag. The MSDN article specifically says you need to do that in order for the <script> tag to run.

Categories

Resources