Save function response in a variable - javascript

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.

Related

running a script inside index.html with some conditions [duplicate]

This question already has answers here:
Dynamically add script tag with src that may include document.write
(16 answers)
Closed 3 years ago.
We have this script which we want to run only if user agent is ReactSnap. I tried doing this but it does not seem to be working.
<script>
if(navigator.userAgent!=='ReactSnap'){
<script src='//cdnt.netcoresmartech.com/smartechclient.js'</script>
}
</script>
The operator you are using in your conditional statement - !== is checking to see if the condition is not true.
The correct syntax is if(navigator.userAgent=="ReactSnap")
You are also trying to write html in a javascript context.
You should create your script tag using javascript, like the below example:
if(navigator.userAgent=="ReactSnap"){ // check userAgent
var script = document.createElement("script"); // create a script tag
script.setAttribute("type","text/javascript"); // set type to js
script.setAttribute("src", "//cdnt.netcoresmartech.com/smartechclient.js") // define src for script tag
document.head.appendChild(script); // load script into document head, or change this to a specific location
}
This solution waits to add the script element to the page until we know the condition is true (tested in Chrome):
<body>
<div>Page content goes here</div>
<script>
let conditionalScript = document.createElement("script");
conditionalScript.innerHTML = "alert('woo!')";
// (But set .src instead of .innerHTML)
let userAgent = 'ReactSnap';
if(userAgent == 'ReactSnap'){
// (But check `navigator.userAgent` instead of `userAgent`)
document.querySelector("body").appendChild(conditionalScript);
}
</script>
</body>
I'd suggest using createElement, changing the source with setAttribute and appending it to the head like this.
if(navigator.userAgent!=='ReactSnap'){
let smartTech = document.createElement('script');
smartTech.setAttribute('src', '//cdnt.netcoresmartech.com/smartechclient.js');
document.head.appendChild(smartTech);
}
You can try something like this:
<script>
if(navigator.userAgent=='ReactSnap'){
var script = document.createElement('script');
script.src = "//cdnt.netcoresmartech.com/smartechclient.js";
document.head.appendChild(script);
}
</script>

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

Inserting a <script> tag dynamically via jQuery

I'm trying to add a widget to the page in run-time. Based on this post, I wrote the code below. Unfortunately, it doesn't show anything. Can anybody tell me why?
<script type="text/javascript">
$(document).ready(function () {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";
// Use any selector
$(".testWidget").append(s);
});
</script>
<div class="testWidget">
</div>
If I put the same script as below, it works and shows some information on the page. However, I should insert the script dynamically, not as static.
<div class="testWidget">
<script src="https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7" type="text/javascript" charset="utf-8"></script>
</div>
You should be getting this warning in the console, Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. Here's a way around that:
<script type="text/javascript">
$(document).ready(function () {
// Save a copy of the document.write method
var oldWrite = document.write;
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";
// After script is loaded, revert document.write to the original
s.onload = function () {
document.write = oldWrite;
};
var $testWidget = $('.testWidget');
// Redefine document.write to make the script's call work
document.write = function (html) {
$testWidget.html(html);
};
$testWidget.append(s);
});
</script>
The script tag you include programatically has to be parsed by the browser. Just by inserting the script tag the included code is not parsed by the JavaScript interpreter.
If you explain what you want to finally achieve I am pretty sure that must be a simpler way to do it.

Script Execution - innerHTML, jQuery html()

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>

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/

Categories

Resources