Disable html/javascripts commands in text fields - javascript

How do I prevent input in texts fields from containing HTML and JavaScript code?
Example: I have an input text field. If the user enters javascript instructions, then they get executed.
How can I modify
<script>alert('aces')</script>
so that it will show up as normal text in my field and not as a alert when i try to list it?

Have you looked into libraries like underscore.js (used by Backbone.js)?
It comes with escape functions that prevents user entered javascript to run.
http://underscorejs.org/#escape and http://underscorejs.org/#unescape
so you would write:
alert(_.escape(USERINPUT));
this becomes even more important when you add user input to your DOM, for security reasons you need to escape inputs (or allow only a selection of harmless tags like < strong >).

Related

How to restrict from entering a decimal value in input type number?

So I want to have an input of type number <input type="number"> and I want to RESTRICT users from ENTERING DECIMAL VALUE
Note: I'm hiding the spin buttons of the input type text. Know more here
EDIT: ANYTHING WILL WORK! EVEN JAVASCRIPT!
I searched a lot but found nothing.
I did find this answer but it basically blocks the use of any other key on the keypad except the number keys, so the basic problems occur such as the user cannot use backspace and cut the number entered, another problem is the user cannot use tab to change focus onto the next input.
Thank You!
Preventing user input can be done with JavaScript. I'd use the input event for catching values, as it's a unified interface, encompassing any input method you can think of keyup, paste, pointer events, touch events, etc...
document.querySelector('input').addEventListener('input', e => {
e.target.value = Math.round(e.target.value.replace(/\D/g,''))
});
<input>
But you really should not do it! For at least the following reasons:
Forbidding user input is, by and large, perceived as disrespectful and drives users away. In short, it reduces any user engagement metric you can think of (funneling, sales, visits, sharing, etc...). Don't take my word for it. Do some A/B testing: present the same form with and without blocking user input and look at the results.
Form elements are just tools to help users give you data. But they are completely by-pass-able. If you give me a form I can send whatever I want using it, by simply opening the browser console. The validation must be done on server side. If you're using the value to do something on client side, sanitize the input value in the method, without changing user input.
A respectful way to inform users decimal values are not valid is by making the input :invalid, using the pattern attribute ( e.g: pattern="[0-9]"), styling accordingly (e.g: :invalid { border-color: red }), and displaying an appropriate message.
Don't delete or block user input. They'll do it themselves if you tell them why the value is invalid.
When following web standards, your solution lasts. When you come up with hacks, there will always be the odd device in which your hack doesn't work. You don't know where things will be in 1-2 years from now, nevermind 5 or 10.
Last, but not least, have a closer look at Constraint Validation. You'll need to know and use it when creating quality UX and accessible forms.
This is one option for creating an input element using javascript to limit the values that can be entered. I create an array of allowed keys, including all the digits, backspace, and tab as you specified. I added an event listener for the keydown event, and if the key pressed is not in the allowed group, I prevent the default action, or prevent the value from being entered.
I also added an event listener to the paste event, as you could right click paste and enter information that does not meet the criteria. Instead of trying to validate pasted values I disable pasting all together.
If you have any questions, please ask.
const allowedKeys = [..."0123456789", "Backspace", "Tab"];
const myInput = document.querySelector("input");
myInput.addEventListener("keydown", e => {
const key = e.key;
const allowed = allowedKeys.includes(key);
if (!allowed) e.preventDefault();
});
myInput.addEventListener("paste", e => e.preventDefault());
<input type="number">

Using a Chrome extension to replace characters spanning more than one line in a Facebook status update

I have created a Google Chrome extension to allow users to select text in a component. This works great for most sites. However, Facebook handles its status updates differently. It seems that even though you are filling in what seems to be a single text box, it is actually using a div > div > span > span construct for every single line in this text box. I have no idea why they chose to do this but it makes replacing multiple lines of text much more complex.
Is there a way to select multiple lines (or even contiguous portions of multiple lines) of text in a Facebook status update and replace the data?
The relevant portion of my code looks like this:
function replace_text(language){
let selection = window.getSelection();
string = selection.toString();
/* This section contains code that uses string.replace to replace characters in the string. */
document.execCommand("insertText", false, string);
}
Based on the way my code works now, if I replace text on a single line I have no problems. But, if I replace text that spans multiple lines I end up with a blank unusable input box. Undoubtedly it is because it is removing portions of the html code. How can I fix my code so that the replacement process works properly not only for other sites but also for Facebook?
As of this moment, the one common theme among all status updates (and comments) are that their texts reside within a single or set of span elements with the attribute data-text set to true. So let's target those:
document.querySelectorAll("span[data-text='true']");
For me, I've typed into the status field 3 lines and comment field 1 line of dummy text. So when I execute the above code into the console it returns an array of those four cumulative lines:
>>> (4) [span, span, span, span]
With that array, I can use the Array.prototype.forEach() method to iterate through the spans and replace the innerText:
document.querySelectorAll("span[data-text='true']").forEach(function(element) {
element.innerText = element.innerText.replace('Lorem ipsum','Hello world');
});
However, it is important to note that these changes are being made in the HTML itself and Facebook doesn't store all of its data directly in the HTML. Therefore it can cause undesirable events to occur when you type text into a field, unfocus, change the text in the field, and refocus that field. When you refocus I believe it grabs data of what the text was, before you unfocused that field, from an ulterior source like React's Virtual DOM. To deter it from doing that, the changes either need to be made after clicking the field (real or simulate) or as the user is typing using some sort of MutationObserver (src).

Get Input Field value using DTM on Submitting a form

I have two input fields that had the user access card and password. and the user click on submit button to authenticate.
I'm using DTM in my app to capture the user navigation but I want also to get the values of those field to my DTM so I would know who the user is.
And here is what I tried but with no luck.
Created Data element as below:
And created Event based rule. But not sure how to get the values to be shown in my report:
Thanks for your help.
Example Form
Since you did not post what your form code looks like, here is a simple form based on what I see in the screenshots you posted, that I will use in my examples below.
<form id='someForm'>
User Name <input type='text' name='userName'><br>
Password <input type='password' name='userPass'><br>
<input type='submit' value='submit' />
</form>
Data Elements
Okay first, let's go over what you did wrong.
1) You said you want to capture two form fields, but you only have one data element...maybe? You didn't really convey this in your question. I just assumed as much because of what you did throughout the rest of the screenshots. But to be clear: you should have two separate data elements, one for each field.
2) The CSS Selector Chain value you used is just input, so it will select the first input field on the page, which may or may not coincide with one of the input fields you are looking to capture. So, you need to use a CSS selector that is unique to the input field you want to capture. Something as simple as input[name="userName"] will probably be good enough (but I cannot confirm this without seeing your site). You will need to do the same for the 2nd Data Element you create for the other input field (e.g. input[name="userPass"])
3) In the Get the value of dropdown, you chose "name". This means that if you have for example <input type='text' name='foo'>, it will return "foo". Since you want to capture the value the user inputs, you should select "value" from the dropdown.
Solution
Putting all the above together, you should have two Data Elements that look something like this (one for the user name field and one for the password field; only one shown below):
Event Base Rule
Okay first, let's go over what you did wrong.
1) The value you specified in Element Tag or Selector is input. You aren't submitting an input field; you are submitting a form. Input fields don't even have a submit event handler! Your Event Type is "submit", so at a minimum, Element Tag or Selector should be form. But really..
2) Ideally, you should use a CSS Selector that more directly and uniquely targets the form you want to trigger the rule for. For example, maybe the form has an id attribute you can target in your CSS Selector. Or maybe the form is on a specific page, so you can add additional conditions based on the URL. What combination of CSS Selector or other conditions you use to uniquely identify your form depends on how your site is setup. In my example form above, I added an id attribute, so I can use form#someForm as the CSS Selector.
3) You checked the Manually assign properties & attributes checkbox, and then added two Property = Value items. This tells DTM to only trigger the rule if the input has a name attribute with value of "userName" AND if it has a name attribute value of "userPass". Well name can't have two values at the same time, now can it!
<input name='foo' name='bar'> <!-- bad! -->
All of this needs to be removed, because again (from #1), you should be targeting a form, not an input field.
4) For good measure, looks like you added a Rule Condition of type Data > Custom, but the code box is empty. The rule will only trigger if the box returns a truthy value. Since there is no code in the box, it will return undefined (default value returned by a javascript function if nothing is returned), which is a falsey value. This also needs to be removed.
Solution
Putting all the above together, the Conditions section of the Event Based Rule should look something like this:
But again, ideally your conditions should be more complex, to more uniquely target your form.
Referencing the Data Elements
Lastly, you can reference the input fields to populate whatever fields in the various Tool sections with the %data_element% syntax. For example, you can populate a couple of Adobe Analytics eVars like this (data element names reflect the examples I created above):
Or, you can reference them with javascript syntax in a custom code box as e.g. _satellite.getVar('form_userName');
Additional Notes
1) I Strongly recommend you do not capture / track this type of info. Firstly, based on context clues in your post, it looks like this may count as Personally Identifiable Information (PII), which is protected under a number of laws, varying from country to country. Secondly, in general, it is a big security risk to capture this information and send it to Adobe (or anywhere else, really). Overall, capturing this sort of data is practically begging for fines, lawsuits, etc.
2) Note that (assuming all conditions met), the "submit" Event Type will track when the user clicks the submit button, which is not necessarily the same thing as the user successfully completing the form (filling out all the form fields with valid input, etc.). I don't know the full context/motive of your requirements, but in general, most people aim to only capture an event / data on successful form completion (and sometimes separately track form errors).

Transfer possibly unsafe user input from hidden input field to DOM

The following is a simplified example of a page a user has created at a site (they created it by filling out a form and then they get a URL for the page; the below is the HTML for the page they created).
In the example, I'm taking the value of a hidden input field and then putting it into the DOM as is. That results in an alert, simulating an XSS attack.
What's the best way to prevent things like this? The value of #sourceinput was previously input by the same or a different user who's viewing the page below, and the user's input wasn't filtered to remove tags. (The actual case involves the jquery.tooltip.js plugin and it's bodyHandler callback; on mouseover a bodyHandler callback would get the hidden input and display it to the user.)
One way to deal with this would be to strip tags on input; I control what goes in the hidden textfield so that would seem to solve it.
Another way would be to strip tags in Javascript, but some of these don't seem to be 100% effective:
Strip HTML from Text JavaScript
Is there some sort of best practice that I'm missing, or are those two the best ways?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<head>
<title></title>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>google.load("jquery", "1.7.1");</script>
<script>
$(document).ready(function() {
var badHTML = $('#sourceinput').val();
$('#destinationdiv').html( badHTML );
//$('#destinationdiv').text( badHTML );
});
</script>
</head>
<body>
<input type="hidden" id="sourceinput" value="<script>alert('hi');</script>" />
<div id="destinationdiv" style="width:10px;height:10px;background-color:red;"></div>
</body>
</html>
UPDATE: The solution I'm going with for now has three parts:
When the page the user has created is saved, I run PHP's strip_tags() on their input. These are just short text strings like titles and blurbs, so few users will expect they can enter HTML. That might not be appropriate for other situations.
When the page the user created is displayed, instead of putting what the user had entered in an input value attribute, I put their input inside a div.
I take the value out of that div using .text() (not .html() ). I then run that through the underscore function (see below).
Testing this out - including simulating skipping the first step - seems to work. At least I'm hoping there isn't something I missed.
Here's the escape function used by Underscore.js, if you don't want to use the entire Underscore library of functions:
var escape = function(string) {
return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
};
Used like
var safe_html = escape("<b>Potentially unsafe text</b>"); // "<b>hello</b>"
$("#destination").html(safe_html);
It's written well and is known to work, so I'd advise against rolling your own.
I would say what you commented out (using text() from jquery is the better option). That will make sure the text stays text which is what you want. Filtering or stripping may have unwanted side effects like removing a mathematical expression in the input (" x is < 5").
Do Nothing.
You are trying to protect the user from himself. There is no way the user A can harm user B. And for all you care, user A might as well type javascript:alert('hi') on the address bar and xss himself. And no matter what javascript escape function you create, a savvy user can always bypass it. All in all, its a pointless pursuit.
Now, if you start saving what the user entered on the server side, then you should definitely filter things. Don't build anything on your own. Depending on your server side language, there are several options. OWASP's AntiSammy is one such solution.
If you do choose to save user entered html on the server side, make sure to run it by antisammy or a similar library before saving it to the database. On the way out, you should simply dump the HTML without escaping, because you know whatever is in the database is sanitized.

HTML & Javascript: Using a customized Text Input for Password input

I want to re-invent the password input in HTML.
Okay, here is the work I'd done:
http://www.symplik.com/password.html
(It just a plain html code, nothing really fancy :>)
The "password" is indeed a text input, and I used the onkeyup event to rewrite the input to masking characters.
There're two problems:
(1) backspace or delete cannot be detected
(2) if I type very fast, some characters cannot be captured promptly.
For problem (1). it is partially solved by checking the length of text in the password field and the stored password. Not a very elegant solution anyway.
For problem (2), I'd tried to insert some time delay function in between but still fail. I'd make the field readOnly after every keyUp but it still behaves the same.
Why not use
<input type='password'>
It masks the input for you. No need for javascript.

Categories