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

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);
}

Related

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.

How to Sanitize JS Input

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"));

Loading a Random Caption from a text file using Javascript and Displaying via HTML

I am trying to load a random caption every time my page is loaded. I have a separate text file and contained on each line is a string. I am new to both html and Javascript, as you will see.
HTML:
<div class="centerpiece">
<h1>DEL NORTE BANQUEST</h1>
<p class="caption"><script src = "js/caption.js"></script><script>getCaption();</script></p>
<a class="btn" id="browse-videos-button" href="#video-list">Browse Videos<br><img src="img/arrow-down.svg"style="width:15px;height:15px;"></a>
</div>
Javascript:
function getCaption()
{
var txtFile = "text/captions.txt"
var file = new File(txtFile);
file.open("r"); // open file with read access
var str = "";
var numLines = 0; //to get the range of lines in the file
while (!file.eof)
{
// read each line of text
numLines += 1;
}
file.close();
file.open("r");
var selectLine = Math.getRandomInt(0,numLines);//get the correct line number
var currentLine = 0;
while(selectLine != currentLine)
{
currentLine += 1;
}
if(selectLine = currentLine)
{
str = file.readln();
}
file.close();
return str;
}
Text in Source File:
We talked yesterday
Freshman boys!
5/10
I'm having a heart attack *pounds chest super hard
The site is for my highschool cross country team in case the text file was confusing.
I am unfamiliar with most syntax and was unable to see if by iterating through the file with a loop if i needed to reset somehow which is why I opened and closed the file twice. Here is a jsfiddle of the specific caption I am trying to change and what my function is in Javascript.
https://jsfiddle.net/7cre9qqj/
If you need more code to work with please let me know and any critiques you may have please dont hold back if it looks like a mess, I am trying to learn after all! Thank you for your help!
The File API allows access to the file system on the client side, so it's not really suited to what you want to do. It's also only allowed to be used in very specific circumstances.
A simple solution is to just run an AJAX request to populate your quote. The AJAX call can read the file on your server, then it's simple to split the contents of the file by line, and pick a random line to display. Since you're open to jQuery, the code is pretty simple:
$.get("text/captions.txt")).then(function(data) {
var lines = data.split('\n');
var index = Math.floor(Math.random() * lines.length);
$("#quote").html(lines[index]);
});
Here's a fiddle that demonstrates it in full; every time it runs it will load a random quote: https://jsfiddle.net/s1w8x4ff/

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!

Problem formating Html string in Javascript to send mail

I am trying to send an email (using Outlook mail) from a jsp page.
Requirement is, when the user clicks on send email button the data stored in a string
(with HTML tags) should be passed to the mailbody.
But the problem is, the text displayed in mail body is not formatted as HTML text.
Could you please suggest how to format it as HTML text in Outlook Doc.
I have used the below code in a function-
function OpenOutlookDoc(whatform,msgBody)
{
outlookApp = new ActiveXObject("Outlook.Application");
nameSpace = outlookApp.getNameSpace("MAPI");
mailFolder = nameSpace.getDefaultFolder(6);
mailItem = mailFolder.Items.add(whatform);
mailItem.Display(0);
mailItem.To = "abc#xyz.com";
mailItem.Subject = "TEST MAIL";
mailItem.Messageclass = whatform;
mailItem.Body = msgBody; //the text here is concatenated with HTML tags
mailItem.Send();
}
Thanks for you upcoming help..
After some google'ing:
The MSDN should help:
http://msdn.microsoft.com/en-us/library/aa171418%28v=office.11%29.aspx
The article includes an example to send html emails using vb-script. Converting that to javascript should not be hard - but since activex only works from within Internet Explorer you might as well use vbscript.
Try adding message.IsBodyHtml = true; to your code.
otherwise u can refer this example.

Categories

Resources