Anemic responses html. Crazy shapes. Examples of weak protection
Translation: Vlad Merzhevich
Everyone knows about web forms, right? We insert a tag, a few, maybe, complete it all with a button and you’re done.
You don't know the half of it. HTML5 defines over a dozen new field types that you can use in your forms. And when I say "use", I mean they can be used right away - without any gimmicks, hacks or workarounds. Don't worry too much, I'm not saying that all these exciting new features are actually supported in every browser. Absolutely not, I don't mean by everyone. In modern browsers, yes, your forms will show everything they are capable of. But in older browsers, your forms will still work, although not to their full potential. That is, these features gracefully degrade in every browser. Even in IE6.
Prompt textI.E. | Firefox | Safari | Chrome | Opera | iPhone | Android |
- | 4.0+ | 4.0+ | 4.0+ | 11.0+ | 4.0+ | - |
The first HTML5 improvement regarding forms is the ability to set prompt text in the input field. This text is displayed in the input field if the field is empty and does not have focus. As soon as you click in the input field (or navigate to it via Tab), the hint text disappears.
You've probably seen the prompt text before. For example, Mozilla Firefox includes suggestive text in the address bar that says "Search Bookmarks and History."
When you click on the address bar, the hint text disappears.
Here's how you can include suggestive text in your forms.
Browsers that don't support the placeholder attribute simply ignore it. No harm or violation.
Ask Professor Markup☞ Q. Can I use HTML markup for the placeholder attribute? I want to insert a picture or maybe change the colors.
A. The placeholder attribute can only contain text, no HTML code. However, there are special CSS extensions that allow you to set the text style in some browsers.
Autofocus fieldsI.E. | Firefox | Safari | Chrome | Opera | iPhone | Android |
- | - | 4.0+ | 3.0+ | 10.0+ | - | - |
Websites can use JavaScript to automatically gain focus on the first form field. For example, on the main page Google.com The field for entering search keywords has autofocus. While this is convenient for most people, it can be annoying for advanced users and people with special needs. If you press space while waiting for the page to scroll, there will be no scrolling because the focus is on the form's input field (it will type space into the field instead of scrolling). If you move focus to another input field while the page is loading, the site's autofocus script may "helpfully" move focus back to the original input field, interrupting your typing and causing you to type in the wrong place.
Because autofocus works through JavaScript, there can be difficulty handling these extreme cases and little options for those people who don't want a web page to "steal" their focus.
To solve these problems, HTML5 introduces the autofocus attribute for all form elements. The autofocus attribute does exactly what it sounds like: as soon as the page loads, it moves focus to the specified field. But since this is just markup and not a script, the behavior will be consistent across all sites. Additionally, browser manufacturers (or extension authors) may offer a way for users to disable autofocus.
Here's how you can set a form field to autofocus.
Browsers that don't support the autofocus attribute will ignore it.
What's happened? Say you want autofocus to work everywhere, not just in fancy HTML5 browsers? You can leave the current script with autofocus, just make two small changes:
- add the autofocus attribute to the HTML code;
- Check if the browser supports the autofocus attribute, and if not, run your own script.
Autofocus with alternative
if (!("autofocus" in document.createElement("input")) ) (
document.getElementById("q").focus();
}
Many web pages wait for window.onload to fire and set focus. But the window.onload event won't fire until all the images have loaded. If your page has a lot of images, such naive scripts will potentially change focus after the user has started interacting with another part of your page. This is why power users hate autofocus scripts.
For example, in the previous section, the autofocus script was placed immediately after the form field it referenced. This is the optimal solution, but it may offend your sensibilities by putting a block of JavaScript code in the middle of the page (or more mundanely, your system may not be as flexible). If you can't insert a script in the middle of the page, you should set focus via a custom event like $(document).ready() in jQuery instead of window.onload .
Autofocus via jQuery
$(document).ready(function() (
$("#q").focus();
}
});
The jQuery custom event fires as soon as the DOM is accessible - that is, it waits for the page text to load, but does not wait for all the images to load. This is not an optimal approach - if the page is unusually large or the network connection is slow, the user may still be interacting with the page before the focus script is executed. But it's still much better than waiting for the window.onload event to happen.
If you agree and are willing to insert a single-statement script into your page's code, this is a compromise that is less nasty than the first option and better than the second. You can use jQuery custom events to set your own events, say autofocus_ready. You can then trigger this event manually as soon as the autofocus field is available. Thanks to E.M. Shtenberg for teaching me this technique.
Autofocus with alternate custom event
$(document).bind("autofocus_ready", function() (
if (!("autofocus" in document.createElement("input"))) (
$("#q").focus();
}
});
$(document).trigger("autofocus_ready");
This solution is optimal, just like the first approach. Focus will be set to the form field as soon as technically possible while the page text is still loading. Part of the application logic (focus in the form field) has been moved from the body of the page to the section. This example is based on jQuery, but the concept of custom events is not unique to jQuery. Other JavaScript libraries like YUI and Dojo offer similar capabilities.
Let's summarize.
- Setting the focus correctly is important.
- If possible, have the browser use the autofocus attribute on the field where you want focus.
- If you are using alternative code for older browsers, define support for the autofocus attribute so that the script only runs in older browsers.
- Set focus as early as possible. Insert the focus script into the code immediately after the form field. If this doesn't bother you, embed a JavaScript library that supports custom events and raise the event in code immediately after the form field. If this is not possible, use an event like $(document).ready() from jQuery.
- Under no circumstances should you wait for window.onload to gain focus.
For more than a decade, forms have contained only a few types of fields. The most common are the following.
All of these field types still work in HTML5. If you "upgrade to HTML5" (perhaps by changing !DOCTYPE ), you won't have to make a single change to your forms. Yay for backwards compatibility!
However, HTML5 defines 13 new field types and there is no reason not to start using them.
The first of these new types of email addresses. It looks something like this.
I was going to write a sentence that started "on browsers that do not support type="email" ..." but stopped. Why? Because I'm not sure if browsers don't support type="email" . All browsers "support" type="email" . They may not do anything special, but browsers that don't recognize type="email" will treat it as type="text" and render it as a normal text field.
I will emphasize how important this is. There are millions of forms on the Internet that ask you to enter your email address, and all of them use . You see a text box, enter your email address into it and that's it. And then comes HTML5, which defines type="email" . Are browsers going crazy? No. Every browser on Earth treats the unknown type attribute as type="text" - even IE6. So you can "refresh" your forms using type="email" right now.
What happens if we say the browser supports type="email" ? Well, it could mean anything. The HTML5 specification does not require any specific user interface for the new field types. Opera adds a small icon to the form field. Other HTML5 browsers like Safari and Chrome render as a text field - the same as type="text" - so your users won't notice the difference (until they look at the source code).
And then there's the iPhone.
iPhone doesn't have a physical keyboard. All “typing” is done by clicking on the on-screen keyboard that pops up at the appropriate time, for example, when you go to a form field on a web page. Apple did something clever with the iPhone's browser. It recognizes some new HTML5 fields and dynamically changes the on-screen keyboard to optimize input.
For example, an email address is text, right? Of course, but this is a special type of text. Thus, almost all email addresses contain the @ symbol and at least one period (.), but they are unlikely to contain a space. So when you're using an iPhone and go to , you'll get an on-screen keyboard that contains a smaller space bar as well as dedicated keys for symbols. And @.
Let me sum it up. There is no downside to immediately converting all your email fields to type="email" . Almost no one will notice this except iPhone users, who probably won't notice it either. But those who notice will smile quietly and thank you for making their job a little easier.
Web addressesA web address—which standards geeks called URLs, except for a few pedants who called URIs—is another type of specialized text. The syntax of a web address is limited to the relevant Internet standard. If someone asks you to enter a web address into a form, they expect something like “http://www.google.com/,” not “125 Farwood Road.” Slashes are common—even Google's homepage has three of them. Dots are also common, but spaces are prohibited. And every web address has a domain suffix like ".com" or ".org".
And so... (drum roll please)... . On iPhone it looks like this.
The iPhone has redesigned its virtual keyboard just as it did for email, but now optimizes it for typing a web address. The space bar has been completely replaced by three virtual keys: slash, period, and ".com" (you can hold down the ".com" key to select a different suffix like ".org" or ".net").
Browsers that don't support HTML5 will treat type="url" as type="text" , so there's no downside to using this type for all fields where you need to enter a web address.
Numbers as countersNext step: numbers. Requesting a number is more complex than requesting an email or web address. First of all, numbers are more complex than you think. Quickly select a number. -1? No, I meant a number between 1 and 10.7 ½? No, no, don't be a fraction, stupid. π? Now you just picked an irrational number.
I would like to note that you are not often asked “just a number.” It is more likely that they will ask for a number in a certain range. You may only want certain types of numbers within that range - maybe integers, but not fractions or decimals or something more exotic like multiples of 10. HTML5 covers all of this.
Choose a number, almost any
Let's look at one attribute at a time.
- type="number" means this is a numeric field.
- min="0" specifies the minimum allowed value for this field.
- max="10" is the maximum allowed value.
- step="2" in combination with the minimum value defines the valid numbers in the range: 0, 2, 4 and so on, up to the maximum value.
- value="6" is the default value. Should look familiar, this is the same attribute that is always used to define form field values. I mention this here as a starting point, that HTML5 builds on previous versions of HTML. You don't have to relearn to do what you've already done.
This is the code for a numeric field. Keep in mind that all of these attributes are optional. If you have a minimum but not a maximum, you can specify the min attribute but not the max attribute. The default step value is 1 and you can omit the step attribute until a different step value is needed. If there is no default value, then the value attribute can be the empty string or even omitted altogether.
But HTML5 doesn't stop there. For the same low, low price of freedom, you get these handy JavaScript techniques.
- input.stepUp(n) increments the field value by n.
- input.stepDown(n) lowers the field value by n.
- input.valueAsNumber returns the current value as a floating point number (the input.value property is always a string).
Display problems? Well, the correct interface for managing numbers is implemented differently in browsers. On iPhone, where typing is difficult, the browser again optimizes the virtual keyboard for entering numbers.
In the desktop version of Opera, the type="number" field appears as a counter with small up and down arrows that you can click to change the values.
Opera respects the min , max and step attributes, so you will always achieve an acceptable numeric value. If you increase the value to the maximum, the up arrow in the counter turns gray.
As with all the other input fields I've discussed in this chapter, browsers that don't support type="number" will treat it as type="text" . The default value will be displayed in the field (as it is stored in the value attribute), but other attributes such as min and max will be ignored. You are free to implement them yourself or use a JavaScript framework that already implements counter management. Check here first.
if (! .inputtypes.number) (
// no native support for field type=number
// might try Dojo or another JavaScript framework
}
A counter is not the only way to represent number input. You've probably also seen a slider that looks like this.
Now you can also have a slider on the form. The code looks strangely similar to a counter field.
All available attributes are the same as for type="number" - min , max , step , value - and mean the same thing. The only difference is the user interface. Instead of an input field, browsers are expected to display type="range" as a slider. At the time of writing, the latest versions of Safari, Chrome and Opera work with this. Unfortunately, the iPhone displays as a simple text field; it doesn't even optimize its on-screen keyboard for entering numbers. All other browsers simply treat the field as type="text" , so there's no reason to start using this type immediately.
HTML 4 does not include date selection via calendar. JavaScript frameworks allow you to get around this (Dojo, jQuery UI, YUI, Closure Library), but, of course, each of these solutions requires “implementing” the framework for any built-in calendar.
HTML5 finally defines a way to enable native date pickers without any scripting. There are actually six of them: date, month, week, time, date + time, and date + time with time zone.
So far, support is... scant.
type="date" | 9.0+ | - |
type="month" | 9.0+ | - |
type="week" | 9.0+ | - |
type="time" | 9.0+ | - |
type="datetime" | 9.0+ | - |
type="datetime-local" | 9.0+ | - |
Here's how Opera displays:
If you need time along with date, Opera also supports:
If you need a month plus a year (for example, the expiration date of a credit card), Opera can display:
Less common, but available, is to select the week of the year via:
Last but not least is the timing with:
Date picker with alternative
...
var i = document.createElement("input");
i.setAttribute("type", "date");
if (i.type == "text") (
// No native date picker support :(
// Use Dojo/jQueryUI/YUI/Closure to create it,
// then dynamically replace the element
}
It's likely other browsers will eventually support these types. Like type="email" and other types, these form fields will appear as plain text in browsers that do not recognize type="date" and its variants. If you want, you can just use , make Opera users happy, and wait for other browsers to catch up. It's more realistic to use this, but check if the browser has native date picker support, and include an alternative solution in the form of a script of your choice (Dojo, jQuery UI, YUI, Closure Library, or other options).
Search windowSo, search. Not just searches from Google or Yahoo (well, those too). Think about any search box, on any page, on any website. Amazon has a search box, Yandex has a search box, most blogs do too. How are they made?
, just like any other text field on the web. Let's fix this.
Search for a new generation
In some browsers you won't notice any difference from a regular text field. But if you're using Safari on Mac OS X, it will look like this.
Did you find the difference? The input field has rounded corners! I know, I know, you can hardly contain your feelings. But wait, there's more! When you start typing type="search" into the field, Safari will insert a small "x" button on the right side of the window. Clicking on the "x" clears the contents of the field. Google Chrome, which has the same technology under the hood, behaves the same way. Both of these little tricks look and behave similar to native search in iTunes and other Mac OS X client applications.
Apple.com uses site search to help the site convey a "macaw-loving" feel. But there's nothing specific to Macs here. It's just code, so every browser on every platform can choose how to render according to the platform's conventions. As with all other new types, browsers that don't recognize type="search" will treat it as type="text" , so there's absolutely no reason not to start using type="search" for all your search boxes today .By default, Safari doesn't apply most styles. If you want to force Safari to treat the search field as a regular text field (so you can apply your own styles), add this rule to your style sheet.
input(
-webkit-appearance:textfield;
}
Thanks to John Lane for teaching me this trick.
Color selectionHTML5 also defines a field that allows you to select a color and returns it in hexadecimal. No browser supports color pickers, which is a shame because I've always loved Mac OS palettes. Maybe one day.
Note translator Opera 11 supports this feature.
Form ValidationIn this chapter, I talked about new form elements and new features like autofocus, but I didn't mention perhaps the most exciting part of HTML5 forms: automatic input validation. Let's look at common problems with entering an email address in a form. You probably have client-side validation through JavaScript, followed by server-side validation through PHP, Python, or another server-side language. HTML5 will never replace server-side validation, but it may one day replace client-side validation.
There are two big problems with email address validation in JavaScript:
Seriously, you will get the address wrong. Determining that a set of random characters is a valid email address is incredibly difficult. The harder you look, the more difficult it becomes. Did I mention that this is very, very difficult? Isn't it easier to hang this headache on your browser?
Opera checks type="email"
Here is a screenshot from Opera 11, although the functionality has been present since Opera 9. The code involves setting the email value for the type attribute. When an Opera user tries to submit a form with , the browser automatically checks the email address, even if scripts are disabled.
HTML5 also offers validation of web addresses with field and numbers with . Number validation takes into account the values of the min and max attributes, so browsers will not allow you to submit the form if you enter a number that is too large.
There is no code that enables form validation in HTML5, it is done by default. To disable validation, use the novalidate attribute.
Don't test me
Browsers have been slow to include support for form validation in HTML5. Firefox 4 will have full support. Unfortunately, Safari and Chrome are only partially implemented: they validate form elements, but do not display any visible messages when a form field fails validation. In other words, if you enter an incorrect (or misspelled) date in type="date" , Safari and Chrome won't submit the form, but won't tell you why it didn't. They will set focus to the field that contains an invalid value, but will not display an error message like Opera or Firefox 4.
Required fieldsI.E. | Firefox | Safari | Chrome | Opera | iPhone | Android |
- | 4.0+ | - | - | 9.0+ | - | - |
Form validation in HTML5 is not limited to the type of each field. You can also specify that some fields are required, such fields must have a value before you can submit the form.
The code for required fields is as simple as can be.
Browsers may change the original appearance of a required field. Here's an example of what it looks like in Mozilla Firefox 4.0.
Additionally, if you try to submit a form without filling out a required value, Firefox will display an information bar saying that the field is required and cannot be empty.
Cross-site script injection attacksIn a cross-site scripting (XSS) attack, an attacker injects malicious code into a legitimate Web page, which then runs a malicious script on the client side. When a user visits an infected page, the script is downloaded to the user's browser and executed there. This scheme has many varieties. A malicious script could access browser cookies, session tokens, or other sensitive information stored in the browser. However, all attacks operate according to the scheme shown in Figure 1.
Figure 1. Figure 1. Typical XSS attack![](https://i2.wp.com/ibm.com/developerworks/ru/library/se-prevent/image001.gif)
In a typical XSS attack, the attacker finds a way to inject a string into the server's Web page. Let's say an attacker injected the following line into a Web page: alert("you are under attack") .
Every time a user visits this page, their browser downloads this script and runs it along with the rest of the page's content. In this case, as a result of running the script, the user will see a pop-up window with the text “you are under attack.”If an attacker was able to exploit an XSS vulnerability in a Web application, they could inject script into the page that would provide access to user account information. In this case, the attacker can perform many malicious actions, for example:
- steal an account;
- spread viruses;
- access your browsing history and clipboard contents;
- gain the ability to remotely control the browser;
- scan and use hardware and software resources and applications on the internal network.
To prevent XSS attacks, the application must encrypt the page output before delivering it to the end user. When the output is encrypted, the HTML markup is replaced with alternative representations − objects. The browser displays these objects but does not launch them. For example, converted to .
Table 1 shows the object names for some common HTML characters.
Table 1. Object names for HTML charactersNon-breaking space | |||
< | Less than | < | |
> | More than | > | > |
& | Ampersand | & | & |
¢ | Cent | ¢ | ¢ |
£ | Lb | £ | £ |
¥ | Jena | ¥ | ¥ |
Euro | € | € | |
§ | Paragraph | § | § |
© | Copyright | © | |
® | ® | ® | |
™ | Trademark | ™ | ™ |
When the browser encounters objects, they are converted back to HTML and printed, but they are not fired. For example, if an attacker inserts the string alert("you are under attack") into a variable field on the server's Web page, then when using the described strategy, the server will return the string alert("you are under attack") .
When the browser downloads the encrypted script, it will convert it to alert("you are under attack") and display the script as part of the Web page, but will not run it.
Adding HTML Code to a Server-Side Java ApplicationTo prevent malicious script code from being rendered along with the page, your application must encrypt all string variables before they are rendered on the page. Encryption simply involves converting each character into the corresponding HTML object name, as shown in the Java code shown in Listing 1.
Listing 1. Converting characters to HTML object names public class EscapeUtils ( public static final HashMap m = new HashMap(); static ( m.put(34, """); //< - меньше чем m.put(60, ""); // >- greater than //The user must match all html objects to the corresponding decimal values. //Object mappings to decimal values are shown in the table below) public static String escapeHtml() ( String str = "alert(\"abc\")"; try ( StringWriter writer = new StringWriter((int) (str.length() * 1.5)); escape(writer, str); System.out.println("encoded string is " + writer.toString()); catch (IOException ioe) (ioe.printStackTrace()); ; return null; ) ) public static void escape(Writer writer, String str) throws IOException ( int len = str.length(); for (int i = 0; i< len; i++) { char c = str.charAt(i); int ascii = (int) c; String entityName = (String) m.get(ascii); if (entityName == null) { if (c >0x7F) ( writer.write(""); writer.write(Integer.toString(c, 10)); writer.write(";"); ) else ( writer.write(c); ) ) else ( writer. write(entityName);The Java code in Listing 1 encodes the HTML string String String "alert(\"abc\)" .
Use the following procedure:
As a result, the following line will appear in the output: alert("abc") .
Table 2 shows the mapping of HTML objects to their decimal values.160 | Non-breaking space | |
60 | < | Less than |
62 | > | More than |
38 | & | Ampersand |
162 | ¢ | Cent |
163 | £ | Lb |
165 | ¥ | Jena |
8364 | € | Euro |
167 | § | Paragraph |
169 | Copyright | |
174 | ® | Decimal value Object Description |
8482 | ™ | Trademark |
Conclusion
Cross-site script injection is one of the most common methods of attacking a user's computer. However, you can significantly reduce an attacker's ability to infect your Web application with malicious code. When building your application, be careful to encrypt all page output values before sending them to the end user's browser.
The object described is a very useful and powerful tool. This object has several methods, their description is given below: Collections: Methods: Properties:Response.Cookies collection
The Cookies collection sets values for cookies. If the specified cookies do not exist, it creates them. If the cookie exists, it takes on a new value and destroys the old one.
Response.Cookies(cookie) [(key) | . attributes ] = value
- Options:
- cookie - Cookie name
- key - Optional parameter. If it is specified, then the cookie is a directory (nested) and the key is a set of values.
- attributes - Specified information about the cookies themselves. This parameter can be one of the following:
value - Specifies the value to be assigned to this key or attribute. | Name |
Description | Domain |
Recording only. If specified, cookies are sent only upon request from this domain. | Recording only. The date on which the cookie expires. This date must be set in order for cookies to be written to the client's hard drive after the session ends. If this attribute is not set, then the cookie expiration date is assumed to be the current date. Cookies will expire immediately after the end of the session. |
HasKey | Only reading. Indicates whether the cookie contains the given key. |
Path | Recording only. If specified, cookies are only sent upon request from this path. If the parameter is not set, the path to the application is used. |
Secure | Recording only. Indicates whether cookies will be protected or not. |
Comment:
If the key cookie is created as shown in the following script,
then the following header will be sent:
Set-Cookie:MYCOOKIE=TYPE1=sugar&TYPE2=cookies
If you assign a value to mycookie without using keys, then this action will destroy the type1 and type2 keys. Eg:
In the previous example, the keys type1 and type2 will be destroyed and their values will be lost. Mycookie will now contain the value chocolate marshmallow.
You can also check the existence of a specific key in the following way:
If TRUE is displayed, then such a key exists; if FALSE, it does not.
Response.Write methodResponse.Write variable_or_value
Response.Cookies(cookie) [(key) | . attributes ] = value
- variable_or_value - Data to be displayed on the browser screen via HTML. This parameter can be of any type supported by VisualBasic Scripting Edition. That is, the data can be of the following types: date, string, character, numeric values. The value of this parameter cannot contain the combination %>. Instead, you can use the equivalent combination %\>. The web server will convert this sequence into the required one when the script is executed.
The following example shows how the Response.write method works to output a message to the client.
I'll just tell you: And your name
The following example adds an HTML tag to a web page. Since this method cannot contain the combination %>, we use the sequence %\>. So an example script:
The output will be the line: