inject JS code into a textarea - javascript

I am trying to show some JS code in a textarea. The code is generated with JS so I am injecting it into the textarea with JS. However, using the <script> tags, causes the script to execute. I thought using < would solve this, but this is simply displaying < instead of <.
Any suggestions how I can do this?
$('myTextarea').set('value', '<script>alert('do something');</script>');

Just separate the script tag into two.
$('myTextarea').val('<script>alert("do something");</scr'+'ipt>');

The next </script> after the opening <script> block closes the script block; whether it's contained with a JS string or not.
To fix you can either split the </script> like so;
$('myTextarea').set('value', '<script>alert('do something');</scr' + 'ipt>');
Or like this (less common, but works, and probably more correct);
$('myTextarea').set('value', '<script>alert('do something');<\/script>');
Furthermore, you also need to fix your quotes;
$('myTextarea').set('value', '<script>alert(\'do something\');<\/script>');
You can see this now working here: http://jsfiddle.net/pK9SK/

Related

Can't append script element to head

Current variant looks like that (I tried solution offered here: Can't append <script> element):
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head").append(s);
Previous variant was:
$("head").append($('<script type="text/javascript" src="js/properties.js"></script>'));
And both of them don't work. "properties.js" is also in "js" folder, but if I remove this part of path, it doesn't change anything.
I also tried to use ' instead " and check addBlock: I had it installed, but it's disabled on this page.
Changing "append" function to "appendChild" also didn't help.
"properties.js" contains just one line:
var PREFIX_URL = "http://localhost:8080/app-rest-1.0.0-SNAPSHOT";
And firstly I declare it in "main.js" to which I, in fact, try to connect this file.
Explain, please, what I'm doing wrong.
Add all your <script> tags right before the closing </body> tag, because when the browser encounters a <script> tag it begins downloading it and stops rendering of the page. So by placing them at the bottom of the page you make sure your page is fully loaded before trying to interact with the DOM elements. Also $("head") returns an array of all the <head> tags. You should also enclose your calls in a $(document).ready() function.
<!-- Your html tags here -->
<script type="text/javascript">
$(document).ready(function(){
var s=document.createElement("script");
s.type="text/javascript";
s.src="js/properties.js";
$("head")[0].append(s);
});
</script>
</body>
I made JSBin example. You can see in console that last script tag is the one you need. So the your code is correct.
If your IDE don't highlight 'var' - it may be error not in javascript. You can place it in a wrong place for example.
Can you provide link to a gist (or pastie.org or smth) for us to better understand your problem.
P.S. The code $("head")[0].append gives me undefined ( note to previous answer)

Javascript/jQuery Dynamic text to link/href replece

I need to replace and convert to URL following words on my entire site; Square-Technology UK. I've done some research into replacing text displayed within a site to replace it with url.
Here is the code:
http://jsfiddle.net/Hgtrh/1/
However it doesn't replace on my website for some reason. Here is the HTML am using.
<div class="main_testimonials">
<div class="c_box"></div>
<div class="main_content_img">
<img src="images/news/thumbs/1184901_10151885560986667_1371257993_n_t2.jpg" alt="News" class="news-category"></div>
<div class="main_bubble_box">
Thank you Square-Technology UK for my new system!!
</div>
</div>
this is an example of different javascipt that works, note the ' and "
echo "<script type='text/javascript'>
$(document).ready(function() {
$('body').removeClass('no-js'); $('#my-carousel-3').carousel({ itemsPerPage: 3, itemsPerTransition: 3, easing: 'swing', noOfRows: 1 }); });</script>\n";
Right managed to solve this very easily. My script didn't allow me to use double quotes inside the echo tag in PHP, which is quite obvious. Alternatively using single quotes does not work using the script I posted at the beginning. However the way to do it is just create another file.js, place the code inside it, and then attach it using the following:
echo"<script type='text/javascript' src='js/test_replace.js'></script>\n";
Did you try this?
$(document).ready(function() {
var thePage = $("body");
thePage.html(thePage.html().replace(/Square-Technology UK/ig, 'Square-Technology UK'));
})
Hope this helps..
Try using a more specific identifier to track what you want to replace instead of tracing the entire DOM to search for what you want to replace:
JS:
$(function() {
var $siteLink = $('.site-link'),
linkHtml = 'Square-Technology UK';
$siteLink.html(linkHtml);
});
HTML:
<span class="site-link"></span>
However since your fiddle seems to work we can only guess what is happening, can you provide more info about what jquery you are running, or how the page is layout.
Here is a Fiddle: http://jsfiddle.net/Hgtrh/4/
It is also worth mentioning just like ikaros45 said, that this is normally not something you would want to do with Javascript, this seems more like something that the templates should be able to deal with.
It works on your fiddler example, but not on your site. I suggest confirming that the JQuery library is loading on your site as expected.
So I managed to solve this very easily. My script didn't allow me to use double quotes inside the echo tag in PHP, which is quite obvious. Alternatively using single quotes does not work using the script I posted at the beginning. However the way to do it is just create another file.js, place the code inside it, and then attach it using the following:
echo"<script type='text/javascript' src='js/test_replace.js'></script>\n";

Print Javascript in Javascript?

I am in the process of making an addon for a software that basically allows you to have 'responsive' adverts, by checking the page size with javascript and then outputting the relevant ad code to the screen.
This works fine for text ad codes, however I've hit a snag when the ad code is javascript - I can't get the user-provided javascript to output to the page and be executed.
Is this possible at all?
Here is some example code:
<div id="admanagerresponsive">
<script type="text/javascript">
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;
if (adWidth >= 728) {
<output ad code>
}
</script>
</div>
The code above will be directly in the page.
Is such a thing possible?
EDIT:
could be any advertiser's code, such as adsense. It'll be user provided, and will be standard html. However, it could contain tags, and these will need to be rendered and outputted correctly...
If you really need to inject add html code containing script tags and you are award of the security problems, i suggest to use a library like jQuery that takes care about the cross browser issues with executing <script> tags added later.
Additionally you need to take care about various pitfalls like:
Html paring is done before script parsing, so no matter where a </script> appears this will immediately end your script.
The examples are important for the situations where you have that code as inline script inside your html page.
Example 1:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
// if you add </script> <b>this is visible as html</b> and everything below is not script anymore
}
</script>
Example 2:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
var string = "<script> var test;</script>";//the same problem here everything behind the closing script tag is html and not script anymore
}
</script>
So if you need to have some script to inject there you need to make the </script> not to be detectable by the html parser:
<script>
adUnit = document.getElementById("admanagerresponsive");
adWidth = adUnit.offsetWidth;if (adWidth >= 728) {
var string = "<script> var test;</sc"+"ript>";//that way the html parser does not detect the closing script tag
}
</script>
A better solution is not to use inline script at all, not only for that reason, but because you should always keep css, js and html separated.
Break it into two ideas. From your HTML above, just call a js function you wrote somewhere else. Initially have that js function be an alert, to verify that works.
Once that works, you have the problem: how can I get custom js for a page? The answer to that is hopefully that you can create and load a (one-off, custom) js file the same way you create an html file. Or, libraries such as now.js could help. Or, there is a script portion of your html page that you understand how to assemble to include the js.
You could even preload all your size possibilities, then have the js routine from the first paragraph pick the right routine to call,

"%3Cscript" vs "<script"

Every once in a while, I'll see an HTML code snippet with:
%3Cscript
where the %3C replaces the <. Is this because the code was auto-generated or needs to display properly in an editor or was it coded that way explicitly for some reason and needs to keep that form on the HTML webpage? In case it is helpful here is the full beginning of the line of code I was questioning:
document.write(unescape('('%3Cscript
Wouldn't the line of code work just fine it you replaced the %3C with a <?
The unescape() Javascript function converts the %3C back to < before it gets written into the document. This is apparently an attempt to avoid triggering scanners that might see the literal <script tag in the source and misinterpret what it means.
When writing javascript in a script tag embedded in html, the sequence </script> cannot appear anywhere in the script because it will end the script tag:
<script type="text/javascript">
var a = "<script>alert('hello world');</script>";
</script>
Is more or less treated as:
<script type="text/javascript">
var a = "<script>alert('hello world');
</script>
";
<script></script>
In the eyes of the html parser.
Like mplungjan said, this is convoluted way and one can simply <\/script> in a javascript string literal to make it work:
<script type="text/javascript">
var a = "<script>alert('hello world');<\/script>";
</script>
This is not related to document.write technically at all, it's just that document.write is a common place where you need "</script>" in javascript string literal.
Also note that "<script>" is indeed totally fine as is. It's just the "</script>" that's the problem which you have cut out from the code.
As mentioned, possible attempt to fool scanners.
A more useful and important one is the
<\/script> or '...<scr'+'ipt>' needed to not end the current script block when document.writing a script inline

Expansion of Struts 2 Tags Messes Up Rendering Of Page

Often times, when I use struts 2 tags, the loading of a page will be incomplete apparently because of single quote or double quote characters from the struts 2 tag interfering with such characters from javascript.
One example I am very eager to get working is as follows:
var me = '<s:a href=\'http://www.google.com\'>Google Link</s:a>';
$('#appnSelect').html(me);
So what I am concerned about is when single and double quotes are inside that me string on the right side of line 1. Ultimately, I need to get <s:select> to work, but this problem seems to creep in with a number of tags like the above example. Replace the <s:a> tag with an <a> tag, and voila, it works. However, when the <s:a> tag gets expanded, the page will incompletely load.
Is there an easy solution somewhere I am missing? One thing I did try was with the theme attribute setting theme="simple" because sometimes that helps me when the output gets rendered incorrectly. That did not work in this case.
Generating HTML from tags like that in the middle of a JavaScript string constant is always going to be an ugly business. In addition to quote characters, you're also likely to get newlines. Strictly speaking you don't know what you're going to get, and you can't control it.
One thing that comes to mind is that you could drop the tags into dummy <script> blocks marked as a non-JavaScript type:
<script id='anAnchor' type='text/html'>
<s:a href='http://www.google.com'>Google Link</s:a>
</script>
The browser won't try to execute that. You can then do this in your JavaScript code:
$('#appnSelect').html($('#anAnchor').html());
What should work with very little thinking:
<s:a id="google" style="display: none;" href="www.google.com">Google Link</s:a>
Now just grab the the element using the id in your script. Might be better if you set up a class. There are id, style and class attributes for all struts2 tags.
I believe the issue is with your escaping of the single quotes inside the <s:a> tag. In my experience with using <s:url>, I've done the following:
var url = "<s:url value='/someAction.action' />"
I believe the same syntax should hold true for <s:a>.
Additionally, look in your JSP container's error log, and see if you can find an error relating to that <s:a> tag. That may provide some additional insight to the problem.
This is my answer, which will not be the best answer because Pointy's response pointed me in the correct direction. However, up votes still appreciated :)
First, you need the script blocks which are not rendered. I have 2 because a checkbox will toggle between which one is displayed:
<script type="myType" id="abc">
<s:select name="selectName" list="#list1" listValue="%{prefix + '-' + name}" theme="simple"/>
</script>
<script type="myType" id="abc2">
<s:select name="selectName" list="#list2" listValue="%{prefix + '-' + name}" theme="simple"/>
</script>
Next, I create a region which is blank in the html code
<div id="innerRegion">
</div>
Then, I need to put something on the screen when the page first comes up, so go with this:
<script type="text/javascript">
$(document).ready(function(){
$('#innerRegion').html( $('#abc').html() )
});
I needed to put this at the end of my document because onLoad was already being used by a parent page. So I am saying abc is the correct default.
Then I need logic to handle what happens when the checkbox is pushed:
var buttonPressed = false;
$(window).load(
function()
{
LocalInit();
});
function LocalInit() {
$('#myForm input[name=buttonValue]').change(
function()
{
buttonPressed = !buttonPressed;
if (buttonPressed == true)
{
$('#innerRegion').html( $('#abc2').html() )
} else
{
$('#innerRegion').html( $('#abc').html() )
}
$('#dataId').href = document.location.href;
}
);
}
I think what was tripping me up ultimately was that I was trying to force the s:select tag through jQuery functions when as you see above it did not turn out to be necessary. I could just write the s:select as normal.

Categories