How to append <script> that will be executed? - javascript

Tried this :
Click me
<div id="pasteContent"></div>
​
var elemFunc = '<script>alert("myString");</script>';
$("#showAlert").click(function () {
$("#pasteContent").html(elemFunc);
});
​
What I'd like to do is to append the string alert(myString); (which is a script) that must be executed... how can I do? Is it not correct?

Add a backslash before / in </script>: http://jsfiddle.net/kxALH/3/
Your code failed, because </script> is considered as a close tag for your fiddle script. As a result, your first fiddle looked somewhat weird.
Note: If you want to execute an arbitrary string of code, $.globalEval('alert("myString")'); may suit better.

try it whit a jquery script object like this
var elemFunc = $('<script>')
.attr('type', 'text/javascript')
.html('alert("myString");');
$("#showAlert").click(function () {
$("#pasteContent").append(elemFunc);
});

Try this:
var elemFunc = '<script>alert("myString");</' + 'script>';
If you have your JS inside your HTML

Try this:
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://somedomain.com/somescript";
$("head").append(s);
Note that the script will load and you can access the variables inside it, but you wouldn't see the actual tag in the DOM.

Since what you're going equates to an eval, and eval IS evil, You can use an external script and $.getScript(), to load it via ajax...
$.getScript("http://scriptURL.com/script.js", function(){ init(); });

Related

Jquery append if location finish with W12345

I need to do a conditional append here is the example url
www.google.com/default.asp/W12345
I want to append a JS file if the url has W and a random string of numbers after it.
How can i achieve this?
Try something like this:
<script>
if (/default\.asp\/W[\d\w]*$/.test(location.href)) {
document.write("<script src='/path/to/your/js/file.js'>");
}
</script>
Insert that code anywhere on the page, typically either in the head, either at the very end of the document.
Use the below snippet on dom-loaded. Here I'm making use of regular expression if it ends with url /wSomeString or /WsomeOtherString.
if(/.+\/w.+$/i.test(window.location.href)) {
var scriptDom = document.createElement("script");
scriptDom.type = "application/javascript";
scriptDom.src = "url/to/js"; //update JS url here.
document.body.appendChild(scriptDom);
}

Append <script> when preparing a html code for iframe: without executing

I am preparing an HTML code on memory for an Iframe, when I use append it executes the code.
html = $(parser.parseFromString($("#EHtml").val(), "text/html"));
js = '<script>' + $("#EJs").val() + '</script>';
html.find('body').append(js);
$("#EHtml").val() contains HTML code
and the append function does its job but also executes the code.
Any thoughts here?
You need to just store a reference to the string of code and do 1 of two things: either do the append interaction only when you want to run the code later, or run eval(jsString) when you want to run it.
Script tags won't execute if their [type] attribute is set to anything wacky.
<script type="wacky/non-executing">
console.log("This will not execute! You will not see this!");
</script>
Its Obvious to run script when you insert it, between script tags,Because your DOM already complete loads.
And it will run twice because you put it inside the body So when you body content canges the script ran again!
So you have to set your Script tag on head of an iframe to it will run Only when you insert it or reload,and not again an again !
I am not suggesting you to use eval() because it is dangerous to use for script evaluation,eval() is basically used for another purpose !
Use <script></script> tags to run your script and place it on head if you don't want to ran it twice .
var script = document.createElement('script');
script.innerHTML = $("#EJs").val();
iframe.contentWindow.document.head.appendChild(script);
May be this will help you..
Try using entities, like
var encodeHtmlEntity = function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
};
html.find('body').append(encodeHtmlEntity(js));
to append and
var decodeHtmlEntity = function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
decodeHtmlEntity(html.find('body').val());
to read.
Got it in the way I need.
I was trying to add the script tag without using ways around the problem - I mean I just wanted to add the tag as it is. Thanks every body for the inputs - I got the solution from your advises...
in the end I could append to the Iframe but it was executing in the main page context. What was causing the problem was using JQuery to do the appending... so here it is:
frame = document.getElementById("frame");
out = (frame.contentWindow) ? frame.contentWindow : (frame.contentDocument.document) ? frame.contentDocument.document : frame.contentDocument;
out.document.open();
out.document.write(html.find('html')[0].outerHTML);//HTML added here
//JS appended here
js=out.document.createElement('script');
js.innerHTML = 'js code here';
out.document.getElementsByTagName("body")[0].appendChild(js);
out.document.close();
I hope its useful for someone...

Is it possible to use a variable for a javascript reference

Instead of:
<script src="/scripts/myJsFile.v1.js" type="text/javascript></script>
Have something like
<script src="/scripts/myJsFile." + versionVar + ".js" type="text/javascript></script>
This way when we update the js version files the user won't have to clear their cache.
Not in that way, because you're mixing HTML and JavaScript together. HTML does not have JavaScript variables available.
What you can do, however, is adding the <script> tag dynamically, i.e. through JavaScript. That way, you obviously are able to use variables:
<script>
var versionVar = "1.0";
window.addEventListener('load', function() { // on load
var scriptTag = document.createElement('script'); // create tag
scriptTag.src = "/scripts/myJsFile." + versionVar + ".js" // set src attribute
scriptTag.type = "text/javascript"; //set type attribute
document.getElementsByTagName('head')[0].appendChild(scriptTag); // append to <head>
}, false);
</script>
Check out how Google loads their Analytics. Then maybe try something similar like:
(function() {
var versionVar = 9;
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.src = 'http://www' + '.google-analytics.com/ga' + versionVar + '.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
You can't do this in your HTML file directly. But still you can do this inside an script tag if versopnVar is a JavaScript variable in your window context:
<script type="text/javascript">
var script = document.createElement('script');
script.setAttribute('src', '/scripts/myJsFile.' + versionVar + '.js');
script.setAttribute('type', 'text/javascript');
document.body.appendChild(script);
</script>
At the end, it's not a good aproach doing this. Please read this article at a list apart to get informed.
Alternative Style: Working With Alternate Style Sheets
It would probably be better to do something like
<script src="/scripts/myJsFile.js?v1" type="text/javascript></script>
Then, when you make and update:
<script src="/scripts/myJsFile.js?v2" type="text/javascript></script>
Which will cause most browsers to pull the file rather than pull from cache. This means that you won't have separate JS files. But will just be forcing the user to pull the most recent.
Also, if you want it to always pull the file you can, in a similar manner, append a random int.
You cannot do that straight out.
One way is with some server side code.
For example in php:
<?php $version = "1.0"; ?>
<script src="/scripts/myJsFile.<?php echo $version ?>.js" type="text/javascript></script>
Not exactly that way, but you can create a new script node with e.g. document.createElement and add it to the page.
var s = document.createElement("script");
s.src = ...
document.body.appendChild(s);
You can also use the document.write call to do the same...
You'd have to update your page to update the variable. Also, you'd have to update your javascript file name every time you changed it.
You can use a query string to make your JS unique.
<script src="/scripts/myJsFile.js?version=2" type="text/javascript></script>
marshall & I had the same Idea.
Also, you'd have to update your HTML file every time you updated your Javascript file.

Reference JS file in JS file

I have a Js function that I would like to:
Reference another js file
Pull a function out.
I would like to do this JS side and not reference on the actual page as I need this process to happen dynamically.
var h = document.getElementsByTagName('head')[0],
s = document.createElement('script');
s.type = 'text/javascript';
s.onload = function () { document.getElementById('hello').innerText = h.innerText; };
s.src = 'http://html5shiv.googlecode.com/svn/trunk/html5.js';
h.appendChild(s);
see: http://jsbin.com/uhoger
If you're working with the browser, jQuery has an helper function for it, $.getScript.
The only option I can think of is to dynamically insert a new script tag into the page targeting your desired script from your initial javascript. Just have your initial script insert the new <script> tag on load, or upon request and then test for availability.

How to include jquery.js in another js file?

I want to include jquery.js in myjs.js file. I wrote the code below for this.
var theNewScript=document.createElement("script");
theNewScript.type="text/javascript";
theNewScript.src="http://example.com/jquery.js";
document.getElementsByTagName("head")[0].appendChild(theNewScript);
$.get(myfile.php);
There shows an error on the 5th line that is '$ not defined'. I want to include jquery.js and then want to call $.get() function in myjs.js file. How can I do this?
Please help me
Appending a script tag inside the document head programmatically does not necessarily mean that the script will be available immediately. You should wait for the browser to download that file, parse and execute it. Some browsers fire an onload event for scripts in which you can hookup your logic. But this is not a cross-browser solution. I would rather "poll" for a specific symbol to become available, like this:
var theNewScript = document.createElement("script");
theNewScript.type = "text/javascript";
theNewScript.src = "http://example.com/jquery.js";
document.getElementsByTagName("head")[0].appendChild(theNewScript);
// jQuery MAY OR MAY NOT be loaded at this stage
var waitForLoad = function () {
if (typeof jQuery != "undefined") {
$.get("myfile.php");
} else {
window.setTimeout(waitForLoad, 1000);
}
};
window.setTimeout(waitForLoad, 1000);
The problem is that the script doesn't load instantly, it takes some time for the script file to download into your page and execute (in case of jQuery to define $).
I would recommend you to use HeadJS. then you can do:
head.js("/path/to/jQuery.js", function() {
$.get('myfile.php');
});
Simple answer, Dont. The jQuery file
is very touchy to intruders so dont
try. Joining other files into jQuery
file will often cause errors in the JS
console, PLUS jQuery isn't initialized
until the file is loaded into main
document.
Sorry, scratch that. Didnt quite know what you were doing.
Try this:
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'http://domain.com/jquery.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
I used this code before, and it worked:
var t=document;
var o=t.createElement('script');
o=t.standardCreateElement('script');
o.setAttribute('type','text/javascript');
o.setAttribute('src','http://www.example.com/js/jquery-1.3.2.js');
t.lastChild.firstChild.appendChild(o);

Categories

Resources