Script Execution - innerHTML, jQuery html() - javascript

document.body.innerHTML = "<script>alert(11);</script>"
$("body").html("<script>alert(11);</script>")
innerHTML is not executed.
jQuery html() is executed.
Why so?

Without getting into the theoretical questions of why jQuery chose to do this, the jQuery html() behaves differently than the native innerHTML. By default, jQuery will find the script tags within the HTML, and load then asynchronously. If this behavior is undesirable, you can use $.parseHTML to prevent this from happening by setting the third argument to false.
$("body").empty().append($.parseHTML("<script>alert(11);</script>", document, false));
Note that the script tags will not be added to the DOM using this method.
Conversely, if you wish to achieve the same affect as your jQuery statement in vanilla JS, you can do the following.
var script = document.createElement('script');
script.text = 'alert(11);';
document.body.innerHTML = '';
document.body.appendChild(script);

Try this...
var x = document.createElement('script');
var y = document.getElementsByTagName('script')[0];
x.text = "alert(11);"
y.parentNode.insertBefore(x, y);

Using innerHTML will stop the script from executing according to the documentation in simple words without going into details.
<script type="text/javascript">
var script = document.createElement('script');
script.appendChild(document.createTextNode("alert('11')"));
document.body.appendChild(script);
</script>

Related

Can't execute inline script with Element.insertAdjacentHTML()

Can I use insertAdjacentHTML to execute inline javascript?
What works in the browser console:
$('body').append('<script>alert(1)</script>')
What I need to work in browser console:
document.body.insertAdjacentHTML('beforeend', '<script>alert(1)</script>');
The VanillaJS solution does not work. I would be glad about a reason
Using insertAdjacentHTML, although the script tag is added to the page, it won't be parsed or executed.
For the script to actually run you need to use createElement:
var script = document.createElement('script');
script.innerText = "console.log('Hello!');";
document.body.append(script);
var script = document.createElement('script'); // create a new script element
script.innerText = "alert('Hello!');"; // InnerText property html-encodes the content,
document.body.append(script); //append innterText to script

Use javascript to append an inline jquery script

I am trying to use a simple vanilla js script within the page to append some jQuery to the end of the body, where it will come after the jQuery lib load and thus work. I can append js to it fine as shown here..
window.onload = function(){
var script = document.createElement('script');
script.text = "alert('ok');";
document.body.appendChild(script);
};
Attemping to append jQuery:
window.onload = function(){
var script = document.createElement('script');
script.text = "$(window).load(function() {";
script.text += "alert('ok');";
script.text += "});";
document.body.appendChild(script);
};
Works fine appending vanilla, breaks with any jQuery. Why?
*the += instead of one line was one suggested fix to this, but with no luck
**Feels like this should be a duplicate and I'm finding similar issues but not specifically inserting (and triggering, which I realise may be a problem) jQuery.

Save function response in a variable

I got this script:
<div id="contenedor1">
<script>
var script = document.createElement("script");
script.type = "text/javascript";
script.text = 'document.write(xmlDoc.getElementsByTagName("INFO")[0]
.getElementsByTagName("CONTENEDOR1")[0].childNodes[0].nodeValue);'
$('#contenedor1').html( script );
</script>
</div>
This script will print the following inside "contender".
<script type="text/javascript">document.write(xmlDoc.getElementsByTagName("INFO")[0].getElementsByTagName("CONTENEDOR1")[0].childNodes[0].nodeValue);</script>
How can I print the response/content of that script inside "contender" -without printing the script to avoid an endless loop.
You can use;
$('#contenedor1').append( script );
This will append response to contenedor1
Why do you mix pure javascript and jquery ?
Change:
$('#contenedor1#').html(script);
By:
document.getElementById('contenedor1').appendChild(script);
Why are you even creating a script element then? If all you want to do is add the node value to that element, then just do that:
$('#contenedor1').html(
xmlDoc.getElementsByTagName("INFO")[0].getElementsByTagName("CONTENEDOR1")[0].childNodes[0].nodeValue
);
There is no need to go through another layer of indirection with the script element.

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/

JavaScript Banner changing

I want to change the behavior of a JavaScript used to display a banner, coming from a central source.
Today I include a script-tag inline in code, like this:
<script type="text/javascript" src="http://banner.com/b?id=1234"></script>
But what that returns is code which uses document.write, like this:
if(condition) {
document.write('<img src="..." />')
}
I want to somehow override this document.write and maybe evaluate the returned code and instead use a JavaScript-framework to bind code to a div-element at DOM ready.
Is there a way to do that? Something like this?:
OnDOMReady() {
BindBanner(1234);
}
BindBanner(bannerId) {
var divTag = document.getElementById('banner_' + bannerId);
divTag.innerHtml = ManipulatedReturenedCode(bannerId);
}
Can JavaScript's prototyping handle something like this?
Edit: It has to be somewhat waterproof cross-platform, cross-browser-compatible, so I don't know if changing document.write is ok.
Yes, you can override document.write. Prototyping is not necessary, you can do it directly on the document object itself. I do this commonly for analysing malware, but it could certainly be used to capture ad script output, as long as the ad script doesn't do any particularly convoluted processing that would turn up the difference between document.write and whatever you replaced it with.
Here's a wrapper that loads an ad onload (slightly later than DOMReady):
<div id="advertgoeshere"></div>
<script type="text/javascript">
function rewrite(w) {
document.getElementById('advertgoeshere').innerHTML+= w;
}
window.onload= function() {
document.write= rewrite;
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://externalsite/ads.js';
document.body.appendChild(script);
}
</script>
Have you tried overriding document.write? I don't have time to try it right now but give this a go:
var foo = document.write;
var bannerCode = '';
document.write = function(str) { bannerCode += str; };
Then include the script file, then do
document.write = foo;
alert(bannerCode);
Why not use jQuery? It has a DOM ready function:
$.ready(function() {
});
Then you can easily manipulate an element using
$("#div_id").html

Categories

Resources