Render javascript that stored in database - javascript

I have in the database table just one column and it's content either javascript link like
<script src="some src"></script>
or javascript code like
<script>
some code
<script>
So my question is it possible to correct render that javascript inside cshtml file?

You can use the Html.Raw method in your view
#model YourViewModel
#Html.Raw(Model.YourScriptContent)
Assuming YourScriptContent is the property of your view model on which you are setting the script content value, in your GET action.
public ActionResult Index()
{
var vm = new YourViewModel();
vm.YourScriptContent = "<script>alert('testing');</script>";
return View(vm);
}
By default, razor will HTML encode the return value of any c# code/expression with the prefix #. But the Raw method will return the markup which is not HTML encoded, which is what you need in this case.
Since you are not HTML encoding when you render it, I am hoping you completely trust the script content values :). Read about script injection attacks if you do not follow the previous statement.

Related

Javascript converts XML characters to &LT and &GT

I am currently using DYMO Label Printing software to print labels. I have previously had the label XML template stored as plain text and it worked fine. But recently I have decided to move to a more dynamic approach so that labels can be edited and modified directly from the database.
So I am currently storing the XML label templates in a simple SQL database table. I set up the viewmodel that contains the XML information, and then access it in Javascript when printing in the View itself.
I previously just tried this:
try {
var labelXml = "#Viewmodel.XMLString"; //Open XML from Viewmodel directly
var labelD = dymo.label.framework.openLabelXml(labelXml);
}
catch(err) {
alert("Couldn't load label");
return;
}
And that did not work.
I did some research and also tried this (placing viewmodel in "text/plain") and then accessing it above.
<script>
try {
var labelXml = $('#label_XML').text();
var labelD = dymo.label.framework.openLabelXml(labelXml);
}
catch(err) {
alert("Couldn't load label");
return;
}
</script>
<script id="label_XML" type="text/plain">
#Viewmodel.XML
</script>
Both of these methods result in this: (<> replaced with &lt and &gt)
How can I simply access a XML string in the database from the viewmodel while avoiding any unwanted conversions? Thanks.
Using #Html.Raw results in this problem:
The first line is read correctly but with each line break it reads as code instead of text. I put the original #Html.Raw in quotes, is there a way to prevent it from attempting to read it as code as shown above?
It looks like you are struggling with HTML Encoding. Have you tried using #Html.Raw(Viewmodel.XML)? That helper should prevent MVC from HTML encoding the content.
Depending on where that XML content comes from, you might be creating an XSS risk, so be careful how you use Html.Raw and consider reading more about it if it does solve this problem for you Is there a risk in using #Html.Raw?

Read in javascript a spring controller model

I have a controller where a JSONObject is passed as parameter. I would like to work with the object "all" in javascript (client side) not in the server side (JSP) so I don't want to get the object with JSP tags.
#RequestMapping(value = { "/dfi/rca" }, method = RequestMethod.GET)
public String getRcaResult(Model model, String flight_id) {
...
JSONObject all = new JSONObject ();
...
model.addAttribute("all",all);
return "dfi/rca";
}
I have a JSP file that import a Javasript file where I use the attribute all but I don't know how to access to it. If I use this code in the JSP file it works properly:
<script type="text/javascript">
var all= "${all}";
</script>
But if I try the same importing a Javascript file in the JSP, it doesn't get anything:
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/all.js"></script>
In all.js:
var rcaresults = JSON.parse('${all}');
Are there any way to read the Spring model attributes in a Javascript file?
Thanks in advance.
JavaScript is run on the client side. Your model model.addAttribute("all",all); does not exist on the client side, it only exists on the server side while you are rendering your .jsp.
If you want data from the model to be available to client side code (ie. javascript), you will need to store it somewhere in the rendered page. For example, you can use your Jsp to write JavaScript assigning your model to JavaScript variables.
e.g <script>var paramOne =<c:out value="${all}"/></script>
when you use src, your browser (and not your backend) will try to fetch the javascript file from
"${pageContext.request.contextPath}/resources/js/all.js"
so the file is not processed by the server as a ModelView.

How to get the whole contents of the file containing a javascript function into a string in the javascript function

For instance, say I have the HTML page index.html. It has a javascript function someFn() (upon onclick) that needs to obtain the entire contents of this page (which also has text fields that are modified by the user. (So as a result, the page contents will be modified from the original content.) Eventually, this someFn() will try to obtain the entire contents of the page in a variable. This variable is then passed on to a PHP script in another file that does the required work. Alternatively, it may output it to a file which is read by the aforementioned PHP script.
The only problem is how the JS function will obtain the page contents in a variable. jQuery alternatives are welcome as long as they don't mess with the workflow of data shown above.
Try using XMLSerializer.serializeToString() Get DocType of an HTML as string with Javascript to retrieve document.doctype as string , document.documentElement.outerHTML to retrieve html of root element of document
var html = new XMLSerializer().serializeToString(document.doctype)
+ document.documentElement.outerHTML;

Pass generated HTML to JavaScript

I'm trying to pass a string of generated HTML from Python to Javascript. This is the simplified version of my view (using Pyramid framework).
#view_config(route_name='view_page', renderer='templates/page.jinja2', permission='view')
def view_cosmeceutical(request):
gen_html = markdown( ingredient.desc )
return dict(gen_html=gen_html)
From this thread, I saw that I can use {{ variable }} in Javascript too, so in my JS file, I have a function that attempts to change the innerHTML of the element with the id 'content-desc'. But all I'm getting is the string {{ genHTML }} instead of the actual variable containing the generated HTML.
function insertHTML() {
genHTML = '{{gen_html}}';
$('#content-desc').html(genHTML);
}
What am I doing wrong?
One good way to pass data and content from the server-side Python to JavaScript are
JSON embeds in HTML
Separate AJAX calls which serve JSON objects as application/json mime
For the embed approach, I would do somethibng along the lines to export data to the page template as JSON:
import json
gen_html = ...
javascript_data = json.dumps(dict(gen_html=gen_html))
return dict(javascript_data=javascript_data)
Then in the page template pass this to JavaScript global variables:
<script>
window.javascriptData = {{javascript_data}}; // Check need to escape HTML in your case
</script>
And then in JavaScript (keep preferably in a separate static .JS file):
$(document).ready(function() {
$('#content-desc').html(window.javascriptData.gen_html);
});
Also, I would not generate HTML for just passing it to JavaScript in the first place. Instead, I would pass raw data to JavaScript as JSON, and then generate HTML on the client-side from this data using client-side templating. This increases the complexity, but is more "clean" and flexible.
Example microtemplating engines for the client-side JavaScript:
DOM tree based JavaScript template engines

Build a Javascript Widget : can I call an aspx?

I'd like to create my own JS widget, which it must be dinamic.
I mean, for example, the html generated from the downloaded script :
<script src="www.mywebsite.it/widget/?ID=2&Category=4" type="text/javascript"></script>
must be different from :
<script src="www.mywebsite.it/widget/?ID=1&Category=5" type="text/javascript"></script>
and the Data into HTML should be taken from Database, on my server. So, I need to call an aspx page that create javascript that will create html? Or which could be the solution?
The better way is to use generic handler with .ashx, if you want retrieve data from server and send data in JSON or XML.
Next, the data will be inserted in page with javascript.
So, if I understand well, you do generate an .aspx that contains your template and a javascript that hold the code to navigate in Category as this if you use JQuery :
$.ajax({
url: 'data.ashx?ID=2&Category=5',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Server behind (ashx) :
private readonly JavaScriptSerializer _js = new JavaScriptSerializer();
public void ProcessRequest(HttpContext context)
{
//Do logic and retrieve data here
Categorys c = GetFooById(context.Request["id"]);
context.Response.Write(_js.Serialize(c));
context.Response.ContentType = "application/json";
}
It seems that you'd want to use AJAX.
The script source shouldn't be dynamic (it can't be cached if it is), but the script itself could call whatever page you like to pull back data (say in JSON format) or raw markup to place in a pre-defined element.
Don't use the ASPX page to create javascript if you can help it.
Consider using a JavaScript library such as jQuery to help you.

Categories