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 وصل کن.
<!doctype html>
<html>
<head>
<title>Guestbook</title>
</head>
<body>
<h2>Guestbook</h2>
<input id="name" placeholder="name">
<input id="msg" placeholder="message">
<input id="site" placeholder="https:// (optional)">
<button id="send" onclick="post()">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; }
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);
list.appendChild(li);
status.textContent = "posted";
}
</script>
</body>
</html>
راهنما و جواب این چالش · برگشت به درس جلسهی 48: پروژه: دفتر مهمان امن · چالش بعدی: Server-Side Escape
بیشتر بخوان: شرط if، elif و else در پایتون: آموزش کامل با مثال