How access parameter passed to HTML page with JavaScript - javascript

I am passing parameter to HTML page with NodeJs router using:
res.render('dashboard', {ph_user: fname});
I can use this parameter in my HTML code with:
<div id="greeting">Welcome: <%= ph_user %></div>
However, i also would like to use this parameters with script on HTML page.
I am sure I can extract if from element by ID, but that doesn't seem like the most efficient way. What is the best way, to access/use parameter in script on HTML page.
Any guidance is greatly appreciated.

You can pass the variables like so:
<script type="text/javascript">
var ph_user = <%- ph_user %>;
// or window.ph_user = <%- ph_user %>
</script>
Be sure you understand the differences and risks between escaped and un-escaped variables. You can put this script above your other scripts and then it will be available to the other scripts.

Related

Client-side Handlebars causes 404 requests

I want to use handlebars on the client side. In my html code I have calls like:
<img src="data/cloud/products/{{key}}/{{images.product.frontal.trans_bg_img}}" alt="">
directly in my index.html.
In javascript I do something like this:
this.emptyPageSource = $("#productdetail").html();
this.productTemplate = Handlebars.compile(this.emptyPageSource);
var html = this.productTemplate(product);
$("#productdetail").html(html);
which works fine. I take the existing piece of html from the dom as a template once, then apply the templating with handlebars and overwrite the old dom entry.
When I load the page, I get a lot of 404 requests, because the browser already tries to load the image resources, even if the templating wasn't invoked yet, due to the JS part.
Is there a way to evade the 404 get requests? (I'm not using angular or something alike - just plain js + jquery)
Thank you in advance
Chris
I will try converting #productdetail element to <script type='text/template' id='productdetail'>. As in: JSBin
<h1>A Cat</h1>
<script type="text/template" id="productdetail">
<img src="{{image}}" alt="">
</script>
Rest of it
<script>
var product = {
key: '1',
image: 'https://media.giphy.com/media/freTElrZl4zaU/giphy.gif'
}
var emptyPageSource = $("#productdetail").html();
var productTemplate = Handlebars.compile(emptyPageSource);
var html = productTemplate(product);
$("#productdetail").replaceWith(html);
</script>
The browser does not understand text/template scripts and just ignores its. But we can read the content inside our script tag use it as a template.

ASP.NET webForm variable binding in markup body

Asp.Net webform 4.5
I am referencing a script with a REV in a master page
<script src="<%# "/content/js/master.js?"+ RevID %>"></script>
RevID is a Public string in code behind.
This use to be in -head- section, and worked very well with
Page.Header.DataBind();
I now wish (as recommended) to move all scripts to the end of body.
when done, Page.Header.DataBind(); does not work anymore and I get src="".
Page.DataBind();
does work BUT it also re bind all control in child pages, so it is not a solution.
so how can I use
<%# ... %>
in the body section without
Page.DataBind();
?
As I have mentioned in the comment, if you want to use the code nuggets with # you will have to call DataBind method. Alternatively, if you have a public string field in code behind like this:-
public string RevID = "3";
Them you can simply access it like this:-
<script src="<%= "/content/js/master.js?"+ RevID %>"></script>
and this should work fine.

javascript loaded from a path; how to use document.getelementbyid

`
function init() {
var a = 'output of my processing';
alert('I am here'); // alert pops up
document.getElementById("<%=hdnField.ClientID %>").value = a;
}
<head>
<script src="../Scripts/myscripts.js"></script>
</head>
<body onload="init()">
<asp:HiddenField ID="hdnField" runat="server" />
</body>
`I have a page with lot of javascript; I am trying to clean it up by moving the scripts to a script folder and reference the path; Seems to work fine, except when it encounters 'document.getelementbyid(controlname.id)'- it throws 'TypeError: Cannot read property 'value' of null'
I understand it is not able to find the control. Why does that happen? I thought the DOM is already built - what difference does moving the javascript to a path make to that anyway? Any ideas on how to make it work? I would really like javascript to be moved from the page.
You're using ASP.Net inline calls inside your JS. This couldn't work, for two reasons:
It's likely you don't have your server configured to handle .js files using the ASP.Net processor.
Even if you did, the processing of the .js would be completely separate to the hosting .aspx page; meaning hdnField would not be in scope.
You would be better off passing knowledge about the items on your page directly to the JavaScript:
JS:
function init(config) {
var a = 'output of my processing';
alert('I am here'); // alert pops up
document.getElementById(config.hdnFieldID).value = a;
}
ASPX:
<head>
<script src="../Scripts/myscripts.js"></script>
</head>
<body onload="init({ hdnFieldID: '<%= hdnField.ClientID %>' })">
<asp:HiddenField ID="hdnField" runat="server" />
</body>
Hope that helps.
This answer assumes your directory structure is correct.
Move your script tag to the bottom of the body, just before . Here is a good SO answer to this question, and here is another.
In addition, in general, it's bad practice to call a JavaScript function from inside HTML elements. If you're not using jQuery, you can add a "DOMContentLoaded" event listener to run the code. With jQuery, the standard $(document).ready() has been proven to work well. Or, if you simply put your script tag at the bottom of the , and place init(); at the end of your JS file, it will all run properly. This would be for a very simple application, but simplicity is sometimes the best.
Finally, for a sanity check, you could hard-code the ID in your init function. I don't know asp.net, but you might want to check the output of <%=hdnField.ClientID %>. Are you sure you're getting the correct ID?
Good luck.

AngularJS Variable From Server Side

I'm writing an ASP.NET application with AngularJS. I have a value that can only be accessed from the codebehind of a page. I'd like to pass this value down so it can be used by an AngularJS controller. I know it's possible to grab URL parameters for use in AngularJS, but I haven't been able to find any other way of getting a value into my controller. Is this possible?
For example, if I have a setup like this:
<%= user.UserDescription %> <%-- this is how I'd get my value from the codebehind --%>
<div ng-app='myApp' ng-controller='myController1'></div>
...
</div>
I want myController1 to have access to user.UserDescription. It's obviously possible to place the value anywhere on the page, by embedding the C# in the ASP.NET page as you see above, but is it possible to pass it into the controller?
I had a similar issue as I had sever side config that I wanted the client side application to know. The solution I came up with is was a config constant that I would add to the bottom of the page. Then loaded that into my services, etc....
Something like this
<html>
<head>
....
</head>
....
<body>
<script>
(function(){
'use strict';
angular.module('myapp.config',[])
.constant('CONFIG', {
user: {
description: '<%= user.UserDescription %>'
}
});
})();
</script>
</body>
</html>

jsp to display alert

How do i write a Jsp page which opens JSbox.
main vulnerabilities that apply to this eg.
I'm just going to worry about the cross-site-scripting problems caused by HTML and JS injection. CSRF doesn't seem to be an issue yet because just alerting “hello” doesn't have any active side-effects that you would have to be logged in to do.
The bonehead way of doing it:
<script type="text/javascript">
alert('Hello, <%= request.getParameter("name") %>');
</script>
This suffers from JS injection because there is no JS-escaping inside a JS string literal:
name=');execute_arbitrary_code();'
and also suffers HTML injection because the enclosing script block can be closed early:
name=</script><script>execute_arbitrary_code();//
Unfortunately there is no standard tag in JSP that will escape text in a JS string literal (that is itself in an HTML script block). You can write and use your own tag to do it, or reuse a library that defines one. For example OWASP ESAPI has:
<script type="text/javascript">
alert('Hello, <esapi:encodeForJavaScript>${param.name}</esapi:encodeForJavaScript>');
</script>
But it is often easier to avoid encoding into JS, and instead push data through the DOM. Because the DOM is plain HTML, you only need normal markup escaping, which JSP has natively in the <c:out> tag.
<input type="hidden" id="name-parameter" value="<c:out value="${param.name}"/>"/>
<script type="text/javascript">
var name = document.getElementById('name-parameter').value;
alert('Hello, '+name);
</script>
This aids in the long-term goal of keeping your JS separate from your markup and server-side code. data- attributes are another good way to pass data from markup to JS.

Categories