How to Sanitize JS Input - javascript

Hi I have a Java Script Code for handle Modals and some input data. Code is working fine but Now I have run into a problem after code scanning. Scanning tool is giving me the Client Potential XSS error and asking me to Sanitize my input.
Error Description:
Method $ at line 484 of public/js/Activity/dailyActivity.js gets user input for the attr element. This element’s
value then flows through the code without being properly sanitized or validated and is eventually displayed to
the user in method $ at line 484 of public/js/Activity/dailyActivity.js. This may enable a Cross-Site-Scripting
attack.
JS Code:
var job_id;
// Delete action
$(document).on("click", ".deleteButton", function() {
var jobcycid = $(this).attr("data-jobcycid");
job_id = $(this).attr("id");
$("#deleteModal").modal("show");
$("#jcId").html(jobcycid);
});
I'm not very good at JS and still at the beginner level. Can anyone tell me how to sanitize this input?
Scan report highlights the following lines:
....
485. var jobcycid = $(this).attr("data-jobcycid");
....
488. $("#jcId").html(jobcycid);

I've found a solution to this.
I have created following function to sanitize any variable generated from HTML value:
// Sanitize and encode all HTML in a user-submitted string
var sanitizeHTML = function(str) {
var temp = document.createElement("div");
temp.textContent = str;
return temp.innerHTML;
};
Then you can use that to sanitize the variable:
var jobcycid = sanitizeHTML($(this).attr("data-jobcycid"));

Related

How to print javascript variables and show them in console?

I'm trying to implement google ads conversion on my website and as per the google team, I added the tags they gave yet the conversion is not showing up properly.
After getting in touch with one of the team members, he told me to correct the code:
So far My code:
I m passing an email value through the URL to the 'Thank-you' page.
I m echoing the value inside a hidden input tag and calling it back using ID in javascript
I can get the value from the input and print it in the console.
<input type="hidden" id="email_for_ads" value="some#email.com">
<script>
var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": email_for_ads
};
console.log(email_for_ads);
</script>
I can see the email id in the console, and I'm sure the value is being fetched.
But he said it should be like below upon inspect :
<input type="hidden" id="email_for_ads" value="some#email.com">
<script>
var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": "some#email.com"
};
console.log("some#email.com");
</script>
I even tried the below code too
var baseUrl = (window.location).href; // You can also use document.URL
var email_for_ads = baseUrl.substring(baseUrl.lastIndexOf('=') + 1);
//var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": email_for_ads
};
console.log(email_for_ads);
yet the same output. I can see the value in the console but on inspect. But he insists that it is that way and could be able to see the email value directly in inspecting itself.
Can someone understand, whether this is possible, if so, how can i do it.
It's possible, but very very weird, and I'd highly recommend against it - it doesn't provide any benefits except, I guess, when debugging, but when debugging it'd be easier to just retrieve the input value.
If you wanted the input value to be printed directly in the <script> tag, you'd have to create the script tag dynamically, either with document.createElement('script') or document.write.
For that to be possible, you'd need another script tag to create the dynamic script tag.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="email_for_ads" value="some#email.com">
<script>
// remove this script tag
document.currentScript.remove();
// append new script tag, with the input value directly in the source code
const email_for_ads_first = $("#email_for_ads").val();
document.write(`
<script>
var email_for_ads = $("#email_for_ads").val();
var enhanced_conversion_data = {
"email": "${email_for_ads_first}"
};
console.log("${email_for_ads_first}");
// log this script tag contents, so you can see what's in it:
console.log(document.currentScript.textContent);
<\/script>
`);
</script>
There's no good reason do this. Please don't.
You may need a server-side rendering technology to generate your email value into your HTML and scripts.
You can consider starting a service in nodejs, get the email value in the request,and in the response,return the email with your html and scripts.

Processing lines and filling fields

I read and search and study, but can't seem to write any JS out of my own head - this should be really simple but it will not work. I keep getting an error about an undefined variable "madlib7.html:411 Uncaught ReferenceError: populatefields is not defined at HTMLButtonElement.onclick"
I start with some urls that I paste into a textarea, then I click a button and first it splits the text into individual lines and stores them in variables. Next, I want to split each line by spaces and populate fields in an HTML form with select words from the resulting array via the use of innerhtml.
I know there is some way of looping through the processes, but I have not figured out how to do that yet so for now I am writing it all out the long way. I have not been able to figure out how to address the error message 'ReferenceError' from above.
Thanks for any and all help
Paul
populatefields(day1, location1, streamid1) {
document.getElementById('PanLinks').value.split('\n');
var streamInfoLine1 = resultArr[0];
var streamInfoLine2 = resultArr[1];
var streamInfoLine3 = resultArr[2];
var streamInfoLine1 = resultArr[3];
var streamInfoLine2 = resultArr[4];
var streamInfoLine3 = resultArr[5];
var streamInfoLine1 = resultArr[6];
var streamInfoLine2 = resultArr[7];
var streamInfoLine3 = resultArr[8];
streamInfoLine1.split(' ');
var day1 = resultArr[0];
var location1 = resultArr[3];
var streamID1 = resultArr[4];
document.getElementById("location1").innerHTML= location1;
document.getElementById("time1").innerHTML= day1;
document.getElementById("streamid1").innerHTML= streamID1;
}
could you use stackoverflow built in code sandbox to include all your code in html, javascript code? it seems like the issue is on your html file madlib7.html, where your onclick listener isn't defined on the button. nor did I see anything from your code that indicates any event listener has been setup to perform that button task. so it's hard to help debug what exactly it is.

JavaScript - Why is innerHTML property displaying as text when it contains HTML?

I have the following bit of JS code being executed in a ASP.CORE View which is intended to basically set the content of an element on the page.
if (notificationBanner) {
var bannerText = unescape("#ViewData.GetClient().GetText("$.resetCredentials.step2.otpSendBanner")");
console.log(bannerText);
notificationBanner.innerHTML = bannerText;
}
The following is being logged in browser console:
<p>A One Time Password (OTP) has been sent to your mobile number below. Enter the OTP in the field below. <strong>The OTP is valid for 10 minutes</strong>.</p>
And the element ends up like this:
However this is not correct, I want the part in <strong></strong> to be bold. Why is it adding it as text?
I was looking for a vanilla JS solution so looking at the post crayon provided. Found a good solution. Thanks for your help.
function decodeHtml(html) {
var txt = document.createElement("textarea");
txt.innerHTML = html;
return txt.value;
}
if (notificationBanner) {
var bannerText = unescape("#ViewData.GetClient().GetText("$.resetCredentials.step2.otpSendBanner")");
console.log(bannerText);
notificationBanner.innerHTML = decodeHtml(bannerText);
}

Use of "switch" in Chrome-app versus in regular webpages

I have a small web application in html/js which works perfectly if you open it in a regular browser. I wanted to adapt the code to be able to run it like a Chrome app (my first Chrome app, by the way), and I did all the necessary changes according to the documentation I read: I got rid of inline js, downloaded local copies of jquery, replaced the onclick with event listeners... Now everything works well inside the Chrome app. There is just one thing that doesn't: a switch selector that updates a variable according to what has been selected in a select list. This works well in the regular webpage, but if you run it inside the Chrome app, it's as if the app is ignoring the switch and never updating the values.
Is there any limitation or anything I should take into account in this case? Can it be possible that I need to structure it in a different way to fit the Chrome app requirements?
The code itself:
In the html file we have a text box, whose value will be modified according to what we select in the list. There is also a second text box disabled that will display the result:
<input type="text" class="ctext" placeholder="DJN code" id="code">
<input type="text" class="ctext" id="ft" disabled="true" >
<select id="combobox">
<option value="tiranastockexchange">TIRANA Tirana Stock Exchange</option>
and so on...
in the .js file we have a function which interacts with the select box in the following way:
function convert() {
var str = document.getElementById('code').value
var root = str.replace(/^.*\/|\.[^.]*$/g, '');
var djticker= "";
var prefix = "";
var ct = "";
var notes = "";
var web = "";
var ex = document.getElementById('combobox');
var selex = ex.options[ex.selectedIndex].value;
switch(selex) {
case "tiranastockexchange":
prefix = "aT";
break;
//and the rest of cases following the same structure...
}
After the switch, if I operate with strings and use the value of prefix, I am still getting value "" instead of "aT", as if the whole switch is ignored. The following is what comes after the switch, just before closing the function:
djticker = prefix+root;
var nfield = document.getElementById("notes");
nfield.value = notes;
var result = document.getElementById("ft");
result.value = djticker;
So if the value of code is ASDF.AS and in the select box you select the value with the value tiranastockexchange , the textbox with the id ft should display aTASDF
For that, I have an event listener attached to a button in the html file with the id convert:
document.addEventListener('DOMContentLoaded', function() {
var cf = document.getElementById('convert');
cf.addEventListener('click', function() {
convert();
});
});
In the other hand, if you run this very same code in a regular html file, it works perfectly.
What could make the difference?
Thanks!

JavaScript to set field in Lotus Notes Web Form

I am trying to have a Wscript agent run when the web form starts in order to set a field with the machine name. I have tried adding this as pass through HTML at the bottom of the form as well as adding it to the onLoad event or the JS Header to no avail. I am a beginner at web enabling a form and adding JavaScript to it in Lotus. Any help would be fantastic. Below is the code:
Field Name: MachineName
{
var ax = new ActiveXObject("WScript.Network");
f.MachineName.value = ax.ComputerName;
}
I guess this is not the complete code. At least one line is missing that defines "f"
The curly brackets have no sense in your code...
In the onload- event of the form, this code should work:
var f=document.forms[0];
var ax = new ActiveXObject( "WScript.Network" );
f.MachineName.value = ax.ComputerName;
Of course this will only work in InternetExplorer as shown here

Categories

Resources