Skip to content

Commit b7310d0

Browse files
bsmthpepelsbey
andauthoredFeb 20, 2025··
fix: Add sandbox attrs to live samples that call prompt() and confirm() (#38253)
* feat(api): better example for window.prompt * feat(api): better example for prompt() * feat(api): better example for prompt() * feat(api): better example for prompt() * feat(api): Revert notes changes to help reviewers * feat(api): Align notes * feat(api): Don't mix quote styles in macros * Apply suggestions from code review Co-authored-by: Vadim Makeev <hi@pepelsbey.dev> --------- Co-authored-by: Vadim Makeev <hi@pepelsbey.dev>
1 parent 1bc73ff commit b7310d0

File tree

7 files changed

+109
-81
lines changed

7 files changed

+109
-81
lines changed
 

‎files/en-us/learn_web_development/core/scripting/strings/index.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -121,12 +121,12 @@ Joining strings together like this is called _concatenation_.
121121

122122
Let's have a look at concatenation being used in action:
123123

124-
```html
124+
```html live-sample___string-concat
125125
<button>Press me</button>
126126
<div id="greeting"></div>
127127
```
128128

129-
```js
129+
```js live-sample___string-concat
130130
const button = document.querySelector("button");
131131

132132
function greet() {
@@ -138,7 +138,7 @@ function greet() {
138138
button.addEventListener("click", greet);
139139
```
140140

141-
{{ EmbedLiveSample('Concatenation_in_context', '100%', 50) }}
141+
{{EmbedLiveSample('string-concat', , '50', , , , , 'allow-modals')}}
142142

143143
Here, we are using the {{domxref("window.prompt()", "window.prompt()")}} function, which prompts the user to answer a question via a popup dialog box and then stores the text they enter inside a given variable — in this case `name`. We then display a string that inserts the name into a generic greeting message.
144144

‎files/en-us/learn_web_development/core/scripting/what_is_javascript/index.md

+6-5
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,15 @@ It is the third layer of the layer cake of standard web technologies, two of whi
4444

4545
The three layers build on top of one another nicely. Let's take a button as an example. We can mark it up using HTML to give it structure and purpose:
4646

47-
```html
47+
```html live-sample___string-concat-name
4848
<button type="button">Player 1: Chris</button>
4949
```
5050

5151
![Button showing Player 1: Chris with no styling](just-html.png)
5252

5353
Then we can add some CSS into the mix to get it looking nice:
5454

55-
```css
55+
```css live-sample___string-concat-name
5656
button {
5757
font-family: "helvetica neue", helvetica, sans-serif;
5858
letter-spacing: 1px;
@@ -71,7 +71,7 @@ button {
7171

7272
And finally, we can add some JavaScript to implement dynamic behavior:
7373

74-
```js
74+
```js live-sample___string-concat-name
7575
function updateName() {
7676
const name = prompt("Enter a new name");
7777
button.textContent = `Player 1: ${name}`;
@@ -82,9 +82,10 @@ const button = document.querySelector("button");
8282
button.addEventListener("click", updateName);
8383
```
8484

85-
{{ EmbedLiveSample('A_high-level_definition', '100%', 80) }}
85+
You can click "Play" to see and edit the example in the MDN Playground.
86+
Try clicking on the text label to see what happens.
8687

87-
Try clicking on this last version of the text label to see what happens (note also that you can find this demo on GitHub — see the [source code](https://github.com/mdn/learning-area/blob/main/javascript/introduction-to-js-1/what-is-js/javascript-label.html), or [run it live](https://mdn.github.io/learning-area/javascript/introduction-to-js-1/what-is-js/javascript-label.html))!
88+
{{EmbedLiveSample('string-concat-name', , '80', , , , , 'allow-modals')}}
8889

8990
JavaScript can do a lot more than that — let's explore what in more detail.
9091

‎files/en-us/web/api/htmltextareaelement/index.md

+23-29
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ browser-compat: api.HTMLTextAreaElement
77

88
{{APIRef("HTML DOM")}}
99

10-
The **`HTMLTextAreaElement`** interface provides special properties and methods for manipulating the layout and presentation of {{HTMLElement("textarea")}} elements.
10+
The **`HTMLTextAreaElement`** interface provides properties and methods for manipulating the layout and presentation of {{HTMLElement("textarea")}} elements.
1111

1212
{{InheritanceDiagram}}
1313

@@ -134,27 +134,25 @@ textarea.no-scrollbars {
134134

135135
### Insert HTML tags example
136136

137-
Insert some HTML tags in a textarea.
137+
Insert some HTML tags in a textarea:
138138

139-
#### JavaScript
140-
141-
```js
139+
```js live-sample___insert-html
142140
function insert(startTag, endTag) {
143-
const textArea = document.myForm.myTxtArea;
144-
const selectionStart = textArea.selectionStart;
145-
const selectionEnd = textArea.selectionEnd;
141+
const textArea = document.myForm.myTextArea;
142+
const start = textArea.selectionStart;
143+
const end = textArea.selectionEnd;
146144
const oldText = textArea.value;
147145

148-
const prefix = oldText.substring(0, selectionStart);
149-
const inserted =
150-
startTag + oldText.substring(selectionStart, selectionEnd) + endTag;
151-
const suffix = oldText.substring(selectionEnd);
146+
const prefix = oldText.substring(0, start);
147+
const inserted = startTag + oldText.substring(start, end) + endTag;
148+
const suffix = oldText.substring(end);
149+
152150
textArea.value = `${prefix}${inserted}${suffix}`;
153151

154-
const newSelectionStart = selectionStart + startTag.length;
155-
const newSelectionEnd = selectionEnd + startTag.length;
156-
textArea.setSelectionRange(newSelectionStart, newSelectionEnd);
152+
const newStart = start + startTag.length;
153+
const newEnd = end + startTag.length;
157154

155+
textArea.setSelectionRange(newStart, newEnd);
158156
textArea.focus();
159157
}
160158

@@ -163,7 +161,7 @@ function insertURL() {
163161
if (newURL) {
164162
insert(`<a href="${newURL}">`, "</a>");
165163
} else {
166-
document.myForm.myTxtArea.focus();
164+
document.myForm.myTextArea.focus();
167165
}
168166
}
169167

@@ -175,42 +173,38 @@ const code = document.querySelector("#format-code");
175173
strong.addEventListener("click", (e) => insert("<strong>", "</strong>"));
176174
em.addEventListener("click", (e) => insert("<em>", "</em>"));
177175
link.addEventListener("click", (e) => insertURL());
178-
code.addEventListener("click", (e) => insert("\n<code>\n", "\n</code>\n"));
176+
code.addEventListener("click", (e) => insert("<code>", "</code>"));
179177
```
180178

181-
#### CSS
179+
Decorate the span to behave like a link:
182180

183-
CSS to decorate the internal span to behave like a link:
184-
185-
```css
181+
```css live-sample___insert-html
186182
.intLink {
187183
cursor: pointer;
188184
text-decoration: underline;
189185
color: #0000ff;
190186
}
191187
```
192188

193-
HTML:
194-
195-
```html
189+
```html live-sample___insert-html
196190
<form name="myForm">
197191
<p>
198-
[&nbsp;
192+
[
199193
<span class="intLink" id="format-strong"><strong>Bold</strong></span> |
200194
<span class="intLink" id="format-em"><em>Italic</em></span> |
201195
<span class="intLink" id="format-link">URL</span> |
202-
<span class="intLink" id="format-code">code</span> &nbsp;]
196+
<span class="intLink" id="format-code">code</span> ]
203197
</p>
204198

205199
<p>
206-
<textarea name="myTxtArea" rows="10" cols="50">
207-
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut facilisis, arcu vitae adipiscing placerat, nisl lectus accumsan nisi, vitae iaculis sem neque vel lectus. Praesent tristique commodo lorem quis fringilla. Sed ac tellus eros. Sed consectetur eleifend felis vitae luctus. Praesent sagittis, est eget bibendum tincidunt, ligula diam tincidunt augue, a fermentum odio velit eget mi. Phasellus mattis, elit id fringilla semper, orci magna cursus ligula, non venenatis lacus augue sit amet dui. Pellentesque lacinia odio id nisi pulvinar commodo tempus at odio. Ut consectetur eros porttitor nunc mollis ultrices. Aenean porttitor, purus sollicitudin viverra auctor, neque erat blandit sapien, sit amet tincidunt massa mi ac nibh. Proin nibh sem, bibendum ut placerat nec, cursus et lacus. Phasellus vel augue turpis. Nunc eu mauris eu leo blandit mollis interdum eget lorem.
200+
<textarea name="myTextArea" rows="10" cols="50">
201+
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut facilisis, arcu vitae adipiscing placerat, nisl lectus accumsan nisi, vitae iaculis sem neque vel lectus. Praesent tristique commodo lorem quis fringilla. Sed ac tellus eros.
208202
</textarea>
209203
</p>
210204
</form>
211205
```
212206

213-
{{EmbedLiveSample('Insert_HTML_tags_example', 600, 300)}}
207+
{{EmbedLiveSample('insert-html', , '300', , , , , 'allow-modals')}}
214208

215209
## Specifications
216210

‎files/en-us/web/api/subtlecrypto/derivebits/index.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ We then use Alice's private key and Bob's public key to derive a secret, and com
149149

150150
#### HTML
151151

152-
The HTML is defines two buttons.
152+
The HTML defines two buttons.
153153
The "Change keys" button is pressed to generate new key pairs for Alice and Bob.
154154
The "Derive bits" button is pressed to derive a shared secret with the current set of key pairs.
155155

‎files/en-us/web/api/window/confirm/index.md

+27-15
Original file line numberDiff line numberDiff line change
@@ -26,30 +26,41 @@ confirm(message)
2626

2727
### Return value
2828

29-
A boolean indicating whether OK (`true`) or Cancel (`false`) was
30-
selected. If a browser is ignoring in-page dialogs, then the returned value is always
31-
`false`.
29+
A boolean indicating whether OK (`true`) or Cancel (`false`) was selected.
30+
If a browser is ignoring in-page dialogs, then the returned value is always `false`.
3231

3332
## Examples
3433

35-
```js
36-
if (window.confirm("Do you really want to leave?")) {
37-
window.open("exit.html", "Thanks for Visiting!");
38-
}
34+
### Confirming before an action
35+
36+
The following example shows how to check the returned value of a confirmation dialog.
37+
When the user clicks the OK button, we call {{domxref("window.open()")}}, and if the user clicks Cancel, we print some text to a {{htmlelement("pre")}} element.
38+
39+
```html live-sample___confirm
40+
<button id="windowButton">Open new tab</button>
41+
<pre id="log"></pre>
3942
```
4043

41-
Produces:
44+
```js live-sample___confirm
45+
const windowButton = document.querySelector("#windowButton");
46+
const log = document.querySelector("#log");
47+
48+
windowButton.addEventListener("click", () => {
49+
if (window.confirm("Do you want to open in new tab?")) {
50+
window.open("https://developer.mozilla.org/en-US/docs/Web/API/Window/open");
51+
} else {
52+
log.innerText = "Glad you're staying!";
53+
}
54+
});
55+
```
4256

43-
![Firefox confirm](firefox_confirm_dialog.png)
57+
{{EmbedLiveSample('confirm', , , , , , , 'allow-modals allow-popups')}}
4458

4559
## Notes
4660

47-
Dialog boxes are modal windows — they
48-
prevent the user from accessing the rest of the program's interface until the dialog box
49-
is closed. For this reason, you should not overuse any function that creates a dialog
50-
box (or modal window). Regardless, there are good reasons to [avoid using dialog boxes for confirmation](https://alistapart.com/article/neveruseawarning/).
51-
52-
Alternatively {{HTMLElement("dialog")}} element can be used for confirmations.
61+
Dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed.
62+
For this reason, you should not overuse any function that creates a dialog box or a modal window.
63+
Alternatively, a {{HTMLElement("dialog")}} element can be used for confirmations.
5364

5465
## Specifications
5566

@@ -64,3 +75,4 @@ Alternatively {{HTMLElement("dialog")}} element can be used for confirmations.
6475
- {{HTMLElement("dialog")}} element
6576
- {{domxref("window.alert()")}}
6677
- {{domxref("window.prompt()")}}
78+
- [Never Use a Warning When you Mean Undo](https://alistapart.com/article/neveruseawarning/) on A List Apart (2017)

‎files/en-us/web/api/window/prompt/index.md

+49-28
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ browser-compat: api.Window.prompt
1010

1111
`window.prompt()` instructs the browser to display a dialog with an optional message prompting the user to input some text, and to wait until the user either submits the text or cancels the dialog.
1212

13-
Under some conditions — for example, when the user switches tabsthe browser may not actually display a dialog, or may not wait for the user to submit text or to cancel the dialog.
13+
Under some conditions (when the user switches tabs, for example) the browser may not display a dialog, or may not wait for the user to submit text or to cancel the dialog.
1414

1515
## Syntax
1616

@@ -34,48 +34,68 @@ A string containing the text entered by the user, or `null`.
3434

3535
## Examples
3636

37-
```js
38-
let sign = prompt("What's your sign?");
37+
### Using a prompt with a message and default value
38+
39+
The following example shows how to check the returned value of a prompt.
40+
When the user clicks the OK button, text entered in the input field is returned.
41+
If the user clicks OK without entering any text, an empty string is returned.
42+
If the user clicks the Cancel button, this function returns `null`.
3943

40-
if (sign.toLowerCase() === "scorpio") {
41-
alert("Wow! I'm a Scorpio too!");
42-
}
44+
```html live-sample___prompt
45+
<button id="signButton">Check star sign</button>
46+
<pre id="log"></pre>
47+
```
4348

44-
// there are many ways to use the prompt feature
45-
sign = window.prompt(); // open the blank prompt window
46-
sign = prompt(); // open the blank prompt window
47-
sign = window.prompt("Are you feeling lucky"); // open the window with Text "Are you feeling lucky"
48-
sign = window.prompt("Are you feeling lucky", "sure"); // open the window with Text "Are you feeling lucky" and default value "sure"
49+
```js live-sample___prompt
50+
const signButton = document.querySelector("#signButton");
51+
const log = document.querySelector("#log");
52+
53+
signButton.addEventListener("click", () => {
54+
let sign = prompt("What's your sign?");
55+
56+
if (sign === null) {
57+
log.innerText = "OK, maybe next time.";
58+
} else if (sign.toLowerCase() === "") {
59+
log.innerText = "Don't be shy, enter your sign!";
60+
} else if (sign.toLowerCase() === "scorpio") {
61+
log.innerText = "Wow! I'm a Scorpio too!";
62+
} else {
63+
log.innerText = `${sign} is my favorite!`;
64+
}
65+
});
4966
```
5067

51-
When the user clicks the OK button, text entered in the input field is returned. If the
52-
user clicks OK without entering any text, an empty string is returned. If the user
53-
clicks the Cancel button, this function returns `null`.
68+
{{EmbedLiveSample('prompt', , , , , , , 'allow-modals')}}
69+
70+
### Prompt messages and default values
5471

55-
The above prompt appears as follows (in Chrome on macOS):
72+
There are multiple ways to use a prompt, using `prompt`, `window.prompt`, and providing a message and default values:
5673

57-
![prompt() dialog in Chrome on macOS](prompt.png)
74+
```js
75+
// open a blank prompt window
76+
sign = prompt();
77+
// open a blank prompt window
78+
sign = window.prompt();
79+
// open a prompt with the text "Are you feeling lucky"
80+
sign = window.prompt("Are you feeling lucky");
81+
// open a prompt with the text "Are you feeling lucky" and "sure" as the default value
82+
sign = prompt("Are you feeling lucky", "sure");
83+
```
5884

5985
## Notes
6086

61-
A prompt dialog contains a single-line textbox, a Cancel button, and an OK button, and
62-
returns the (possibly empty) text the user entered into that textbox.
87+
Dialog boxes are modal windows — they prevent the user from accessing the rest of the program's interface until the dialog box is closed.
88+
For this reason, you should not overuse any function that creates a dialog box or a modal window.
89+
Alternatively, a {{HTMLElement("dialog")}} element can be used for confirmations.
6390

64-
Please note that result is a string. That means you should sometimes cast the value
65-
given by the user. For example, if their answer should be a Number, you should cast the
66-
value to Number.
91+
A prompt dialog contains a single-line textbox, a Cancel button, and an OK button, and returns the (possibly empty) text the user entered into that textbox.
92+
The result is a string, which means you should sometimes cast the value given by the user.
93+
For example, if their answer should be a Number, you should cast the value to Number.
6794

6895
```js
6996
const aNumber = Number(window.prompt("Type a number", ""));
7097
```
7198

72-
Dialog boxes are modal windows; they
73-
prevent the user from accessing the rest of the program's interface until the dialog box
74-
is closed. For this reason, you should not overuse any function that creates a dialog
75-
box (or modal window).
76-
77-
Alternatively {{HTMLElement("dialog")}} element can be used to take user inputs.
78-
7999
## Specifications
80100

81101
{{Specifications}}
@@ -89,3 +109,4 @@ Alternatively {{HTMLElement("dialog")}} element can be used to take user inputs.
89109
- {{HTMLElement("dialog")}} element
90110
- {{domxref("window.alert", "alert")}}
91111
- {{domxref("window.confirm", "confirm")}}
112+
- [Never Use a Warning When you Mean Undo](https://alistapart.com/article/neveruseawarning/) on A List Apart (2017)
-22.6 KB
Binary file not shown.

0 commit comments

Comments
 (0)
Please sign in to comment.