Is it possible to insert rendered ASP.NET controls with JavaScript? - javascript

I'm not very familiar with ASP.NET, so forgive me if I word this question poorly. We build lots of .aspx pages that include dynamic "labels" that render as plain text when viewed in the browser. For example, if the source of my .aspx contains this code:
<p>Thanks for trying <em>{ProductName}</em>!</p>
The page when viewed in the browser will read:
Thanks for trying My Company's Product!
Now, I want to able to insert that text on the page dynamically via JavaScript. The problem is that if I have a script write that same bit of code to the page, I get this:
Thanks for trying {ProductName}!
I assume this is because the page has already finished rendering before the script runs, so the dynamic label gets treated as plain text instead of rendering on the server side first.
Is there any way at all that I can do this?

The .aspx scripts are server side rendered, so they are rendered at your web server and then downloaded by the user, so the user already gets a page with that values.
On the other side, javascript is rendered at the client machine, so he downloads the script, and the browser renders the page, thats why you dont get that value show.
There are some workarounds to do that.
First, and the better one is to try ajax. That means that the javascript will do another server request to get that value and show it to the user, and that value will come from server.
Second, you can try to put these server variables on script variables or hidden html elements. That way, when you want to use that values, you can get it from the local script(javascript). It would be something like writting the value on a hidden or hidden input " >, and recover it like
document.getElementById("value_id").innerHTML or even set the javascript variables at your page, doing something like
var val = "<%=ProductName%>";

I'm not familiar with that syntax. I would expect something like <%= ProductName %> instead. What flavor of ASP.Net are you using? WebForms? MVC? Spark?
Since curly braces are integral to the JavaScript language, it is likely that JavaScript tags are not parsed for string replacement. It would take a pretty robust parsing engine to know when the curly braces indicate a string replacement and when they are part of the JavaScript code. If you can switch to the <%= ProductName %> syntax for your JavaScript, that may be the easiest. If that's not an option or doesn't work for your situation, try putting the strings in the html, and extracting them from JavaScript. A hidden input seems ideal:
<input type="hidden" id="ProductName" value="{ProductName}" />
You may find it doesn't work in attributes. Fine, just use a hidden span:
<span class="hidden" id="ProductName">{ProductName}</span>
(don't forget to define a "hidden" css class to do the actual hiding: .hidden { display: none; })
Get at your strings with JavaScript:
var productName = document.getElementById("ProductName").value; // hidden input
var productName = document.getElementById("ProductName").innerHTML; // hidden span

Related

Stop Script Outputting as plain text so that it runs as a Script in a set Div parent Class

I'm trying to output a script via a CMS (Webflow) but the system is outputting it as plain text, which stops it from correctly embedding & running.
So for example rather than getting:-
<div clss="embed"><script type="text/javascript">whatever</script></div>
The output comes out as the same in the inspector, but just plain text (not running script):-
<div clss="embed">"<script type="text/javascript">whatever</script>"</div>
So my question is whether there is a way to target a specific container div with class '.embed' (in Javascript or jQuery) to always ensure that any code in that class is always correctly outputted as a functioning script, rather than just printed on the screen as text?
Thanks
Glennyboy
Example Script
<script type="text/javascript">
var uri = 'https://impgb.tradedoubler.com/imp?type(js)g(228862)a(28418)' + new String (Math.random()).substring (2, 11);
document.write('<sc'+'ript type="text/javascript" src="'+uri+'" charset=""></sc'+'ript>');
</script>
Outputs on the page the same except in speech marks in the code " "
What you are trying to do, and the way you want to do it, is NOT possible. You cannot have a div or container to ALWAYS have FUNCTIONING javascript. The key here is FUNCTIONING. Based on what you are describing, the script you are trying to execute is probably escaped, and so it is not valid javascript.
To really achieve what you are trying to do (which, I assume, is to execute your script dynamically), you need to look at where you are getting that script from. It seems like the source you are using is escaping the javsacript. You will need to un-escape it, and then put it in a script tag dynamically.
Perhaps you could show a little more of your code, so we can see where you are getting the script from. We can probably make a suggestion as to how to properly un-escape it.

Jade / Pug: Hide div unless variable has data

I want to hide a div unless the div has received data to the local variable. I have this at the moment:
div#cost
p You earn #{cost} a day!
But it displays on the page. How do I hide it until it receives the data? Im confused about Jade's if/else syntax
-if (cost)
div#cost
p You earn #{cost} a day!
First of all, the - means that it is unbuffered Javascript code. Meaning this will not get rendered in the final version of the template. If you would want that, you should use a script tag like so: script..
Second, the if-statement will check if cost is not equal to null or undefined. When it doesn't exists, the code inside the if-statement will be skipped.
The above code will result in the following HTML if cost is not equal to null or undefined:
<div id="cost">
<p>You earn ... cost a day!</p>
</div>
What you are trying to achieve is not possible.
jade/pug is a template engine, you can give placeholder variable, perform loops, conditions etc but your browser does not understand jade/pug it understands only HTML, which means your template will be converted to a static HTML content before being displayed.
The if/else block decide what is going to be part of the generated HTML file, once the file is generated jade/pug does not have any control over it.
If you want to dynamically control your DOM you can use a web framework such as Angular, Vue, React or you can do DOM manipulation using jQuery or by hand with regular Javascript.

Inserting Text Into HTML

What I Want: Very simply I have a C program that generates a variable periodically, I want to be able to display this value on a website.
Restrictions: The webpage is HTML, php does not work, javascript does [I have tried a few javascript solutions but they have all been long, tedious and in the end ineffective] I want it to be able to format the text so that it matches the rest of the webpage. Above all I'd really like to find something simple that works.
Freedoms: I can output the variable from my C program to just about any file type and content that I want, the file is hosted so is available locally to the server or online for the client.
Preferred Solutions: I am currently playing around with the object and iframe tags native to html. They give a nice simple input:
<object height=20 width=75 type='text/plain' border=0 data="URL/filename.txt"></object>
inserts the contents of my file, but it can't be formatted so I am stuck with 12pt Courier font which is not acceptable. Using
<iframe seamless height=20 width=75 scrolling='no' src="URL/filename.htm"></iframe>
and adding my desired font/colour/size etc to the htm file gets me the right text style, but htm has a large amount of white padding around it which I can't seem to get rid of so I have to make my iframe quite large for the text to be displayed, but then it doesn't fit smoothly with other text.
So anyone that can answer one of four questions:
How to remove excess padding from htm
How to format the style of a html object
Is there anything in Java as simple as the php [so apparently it doesn't show php code even when you quote it as code. But basically using echo and get_file_contents to insert the contents of a txt file into a html page]
Propose an alternate solution
Padding and style can be handled by css.
By java I assume you mean javascript - google-ing will help you. Without details of what your server is running and what is dispatching your pages we can't give you an exact answer. You might want something with ajax to keep it updating in the background.
Try googling your question, you'd be surprised how often this helps.
I'm not sure what you're trying to do once you get the variable into your web page, but I think something like the following could be useful.
Create a hidden div on your page
Have your C application write the variable to some file
Use jquery to execute an ajax call to pull that value into the div ( or whatever other container you want to use
using some type of timer, execute the ajax call every X period of time, which will then get your up to date variable
on your main page, have another timer that will then come in to that container, grab your value and then you are free to do what you want with it.
This is all off the top of my head without knowing much about what you're trying to accomplish. If you provide some further details we may be able to help you a little more.
You need AJAX... that's just a fancy buzz-word. It means you can tell JavaScript can get a file from the server without reloading the page and you can insert data from that file into your HTML.
AJAX is made much simpler by using a JavaScript library like jQuery, but it can be done without jQuery. There's a pretty decent Getting Started tutorial at Mozilla Developer Network if you want to do it the hard way, but I really recommend jQuery.
As far as formatting... any formatting... you need to use CSS. Just about everything about the appearance of anything on a web page is controlled by CSS. MDN has a Learn CSS section, too.
load jquery on you main html file
put a div with some id (example id="newvalue")
make you c program to write the output in a file (for example value.html)
on main html page header, after jquery include code add some javascript like
$( document ).ready(function() {
$("#newvalue").load('yoursiteurl/value.html');
});

How to create an independent HTML block?

I want to know if there is some way to create an independent HTML block .
For more explanation :
My problem is that I have a webpage in which I allow some users can add content (may contain HTML & CSS )
I allow them to add their content inside a certain block , but sometimes their content may not be clean code , and may contain some DIVS with no end , Or even some DIV end with no starting DIV
This sometimes distort my page completely
Is there any way to make their content displayed independently from my parent div , so that my div is first displayed well , and then the content inside it is displayed ?
I'm sorry for long message .
Thanks for any trial to help
sometimes their content may not be clean code , and may contain some
DIVS with no end , Or even some DIV end with no starting DIV This
sometimes distort my page completely
The easiest solution for you is going to be to add the submitted content to your page inside an <iframe>. That way, it doesn't matter if the submitted HTML is invalid.
If you have to worry about users possibly submitting malicious content (such as JavaScript), the problem becomes much harder: you need to sanitize the HTML. I can't tell you how to do this without knowing what server-side language you're using.
My problem is that I have a webpage in which I allow some users can add content (may contain HTML & CSS ) I allow them to add their content inside a certain block , but sometimes their content may not be clean code , and may contain some DIVS with no end , Or even some DIV end with no starting DIV This sometimes distort my page completely
If that is the problem you are trying to solve, then having some markup to say a chunk of code was independent wouldn't help: They might include the "End of independent section" code in the HTML.
If you want to put the code in a page, you need to parse it, sanitise it (using a whitelist) to remove anything potentially harmful and then generate clean markup from the DOM.
you could use Static iframes.
check this out http://www.samisite.com/test-csb2nf/id43.htm
The safest way is to restrict the tags they can submit, and validate/sanitize those that they do, similar to the way we can use markup on here.
Having unchecked HTML injected into your page is asking for trouble.
Failing that, good old iframe will do the trick.
Okay, i belive there is something you can do, but it can require some time. You can use a parser to go through the users html, and get the tags and their content, and recreate the html making it clean.
But, as there are a lot of tags that can be used, or even invented tags, than you can limit the tags that the user are able to use in their html. You put a legend with the acceptable tags.
There are some pretty good html parsers for php, but they may break for some very bad html code, so this is why i suggest you just recreate it based on the parsing with a limited subset of acceptable tags.
I know it's a difficult/time consuming solution, but this is what i have in mind

Disable JavaScript in iframe/div

I am making a small HTML page editor. The editor loads a file into an iframe. From there, it could add, modify, or delete the elements on the page with new attributes, styles, etc. The problem with this, is that JavaScript (and/or other programming languages) can completely modify the page when it loads, before you start editing the elements. So when you save, it won't save the original markup, but the modified page + your changes.
So, I need some way to disable the JavaScript on the iframe, or somehow remove all the JavaScript before the JavaScript starts modifying the page. (I figure I'll have to end up parsing the file for PHP, but that shouldn't be too hard) I considered writing a script to loop through all the elements, removing any tags, onclick's, onfocus's, onmouseover's, etc. But that would be a real pain.
Does anyone know of an easier way to get rid of JavaScript from running inside an iframe?
UPDATE: unless I've missed something, I believe there is no way to simply 'disable JavaScript.' Please correct me if I'm wrong. But, I guess the only way to do it would be to parse out any script tags and JavaScript events (click, mouseover, etc) from a requested page string.
HTML5 introduces the sandbox attribute on the iframe that, if empty, disables JavaScript loading and execution.
Yes, your update is correct. You must assume that any input you receive from the user may contain malicious elements. Thus, you must validate on the server before accepting their input.
You can try the same solution adopted by CKEditor, of which you have a demo here.
By switching from RTE mode to view source mode, you can enter some JavaScript and see the result, which is a replacement of the JS node in a safely encoded string.
If you are in view source mode, by entering some JS line like:
<script type="text/javascript">
// comment
alert('Ciao');
</script>
you will see it rendered this way when going back to rich text editor mode:
<!--{cke_protected}%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0D%0A%2F%2F%20comment%0D%0Aalert('Ciao')%3B%0D%0A%3C%2Fscript%3E-->
I think it is one of the easiest and effective way, since the RegExp to parse JS nodes is not complex.
An example:
var pattern = /<script(\s+(\w+\s*=\s*("|').*?\3)\s*)*\s*(\/>|>.*?<\/script\s*>)/;
var match = HTMLString.match(pattern); // array containing the occurrences found
(Of course, to replace the script node you should use the replace() method).
Regards.
You can set Content Security Policy as script-src 'self' in header. CSP will block any scripts other than from our own website. This way we can prevent any scripts from iframe changing the elements in our page.
You can get more information from here http://www.html5rocks.com/en/tutorials/security/content-security-policy/

Categories

Resources