جواب «Step 4: Links and CSP» چالش 4 از جلسهی 48
سؤال
لایهی آخر. (۱) یک کادر #site به فرم اضافه شده: اگر خالی نبود و با https:// شروع میشد، به li یک <a> با href و متن همان آدرس اضافه کن؛ اگر خالی نبود ولی با https:// شروع نمیشد، کل پیام را رد کن و #status را bad link کن. (۲) در <head> یک CSP با default-src 'none'; script-src 'nonce-k1x9' بگذار؛ اسکریپت از قبل nonce دارد ولی دکمه هنوز onclick دارد، پس آن را با addEventListener وصل کن.
راهنما
ترتیب اعتبارسنجی: خالی، بلند، لینک بد. بعد از ساختن span، اگر site پر بود const a = document.createElement("a"); a.href = site; a.textContent = site; li.appendChild(a);.
یک جواب درست
<!doctype html>
<html>
<head>
<title>Guestbook</title>
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-k1x9'">
</head>
<body>
<h2>Guestbook</h2>
<input id="name" placeholder="name">
<input id="msg" placeholder="message">
<input id="site" placeholder="https:// (optional)">
<button id="send">Send</button>
<p id="status">-</p>
<ul id="list"></ul>
<script nonce="k1x9">
function post() {
const name = document.getElementById("name").value;
const msg = document.getElementById("msg").value;
const site = document.getElementById("site").value;
const status = document.getElementById("status");
const list = document.getElementById("list");
if (name.trim() === "" || msg.trim() === "") { status.textContent = "empty"; return; }
if (msg.length > 20) { status.textContent = "too long"; return; }
if (site !== "" && !site.startsWith("https://")) { status.textContent = "bad link"; return; }
const li = document.createElement("li");
const who = document.createElement("b");
who.textContent = name + ": ";
const what = document.createElement("span");
what.textContent = msg;
li.appendChild(who);
li.appendChild(what);
if (site !== "") {
const a = document.createElement("a");
a.href = site;
a.textContent = site;
li.appendChild(a);
}
list.appendChild(li);
status.textContent = "posted";
}
document.getElementById("send").addEventListener("click", post);
</script>
</body>
</html>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن