Pastebin
API
tools
faq
paste
Login
Sign up
Please fix the following errors:
New Paste
Syntax Highlighting
Below is a **drop‑in replacement** for the `openDetail()` routine (and a quick refresher on how to reuse the same escaping helper that we already introduced for the card rendering). Everything that is inserted into the DOM – titles, text blocks, lists, etc. – is first run through the same `escapeHTML()` routine so that any `<script>` or other harmful markup that might sneak into the JSON file can’t be executed. ```javascript /* -------------------------------------------------------------------- Utility – escape HTML (kept in the global scope so that all helpers can reuse it). This is the same function we used in `renderCard()`. -------------------------------------------------------------------- */ function escapeHTML(str) { return String(str) .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } /* -------------------------------------------------------------------- Rendering the cards (kept the same – just a reminder that it uses the helper). It is unchanged except for the `escapeHTML()` calls. -------------------------------------------------------------------- */ function renderCard(book) { const title = escapeHTML(book.title); const card = ` <div class="card" data-id="${escapeHTML(book.id)}"> <h3>${title}</h3> <div class="card-body"> <h4>${escapeHTML(book.title)} – ${escapeHTML(book.author)}</h4> <p class="card-text">${escapeHTML(book.blurb)}</p> </div> </div>`; return card; } ``` --- ### 1. The new `openDetail()` implementation ```javascript /* -------------------------------------------------------------------- Global variable that will hold the currently shown detail pane. -------------------------------------------------------------------- */ let activeDetailView = null; /* -------------------------------------------------------------------- 1⃣ Build the content **with escaping** and return it as a `template` element. Using a <template> gives us a cheap sandbox where we can create children with *textContent* – no chance of injecting raw HTML. -------------------------------------------------------------------- */ function openDetail(id) { const result = playbooks.find(b => b.id === id); if (!result) return; // ---------- 1. Build the steps list -------------------------------- const stepsContainer = document.createElement('ul'); stepsContainer.className = 'detail-steps'; result.steps.forEach(step => { const li = document.createElement('li'); li.textContent = step; // <– safe: textContent escapes everything stepsContainer.appendChild(li); }); // ---------- 2. Build the whole detail pane ------------------------ const detailContainer = document.createElement('div'); detailContainer.className = 'detail-view'; detailContainer.setAttribute('data-id', result.id); // 2a. A small “Close” button that simply removes the pane const closeBtn = document.createElement('button'); closeBtn.className = 'detail-close'; closeBtn.textContent = '×'; // × looks nicer than “Close” closeBtn.onclick = closeDetail; // will be defined below detailContainer.appendChild(closeBtn); // 2b. Add the heading (escaped!) const heading = document.createElement('h2'); heading.textContent = result.title; detailContainer.appendChild(heading); // 2c. Add the blurb (escaped!) const blurb = document.createElement('p'); blurb.textContent = result.blurb; detailContainer.appendChild(blurb); // 2d. Append the steps list detailContainer.appendChild(stepsContainer); // 2e. (Optional) Add a little bit of styling if you want the pane // to sit on top of the page detailContainer.style.position = 'fixed'; detailContainer.style.top = '20px'; detailContainer.style.left = '50%'; detailContainer.style.transform = 'translateX(-50%)'; detailContainer.style.background = '#fff'; detailContainer.style.padding = '1rem 2rem'; detailContainer.style.boxShadow = '0 4px 12px rgba(0,0,0,.15)'; detailContainer.style.zIndex = 9999; // ---------- 3⃣ Add the pane to the document ---------------------- document.body.appendChild(detailContainer); activeDetailView = detailContainer; // keep a handle so we can close it // ---------- 4⃣ Highlight the corresponding card ---------------- const highlightedCard = document.querySelector(`.card[data-id="${id}"]`); if (highlightedCard) highlightedCard.classList.add('highlight'); } /* -------------------------------------------------------------------- Closes the detail pane – removes the highlight on the card and removes the detail element from the DOM. -------------------------------------------------------------------- */ function closeDetail() { if (activeDetailView) { const id = activeDetailView.getAttribute('data-id'); const card = document.querySelector(`.card[data-id="${id}"]`); if (card) card.classList.remove('highlight'); activeDetailView.remove(); activeDetailView = null; } } /* -------------------------------------------------------------------- Wire the “Search” results (or any other trigger) to the new routine. -------------------------------------------------------------------- */ searchInput.addEventListener('input', () => { const query = searchInput.value.trim(); displaySearchResults(query); }); /* -------------------------------------------------------------------- When a user clicks a search result, open its detail pane. -------------------------------------------------------------------- */ document.addEventListener('click', event => { if (event.target.closest('.search-result')) { const target = event.target.closest('.search-result'); const id = target.dataset.id; openDetail(id); } }); ``` --- ### 2. How it protects against XSS 1. **All strings from the JSON are inserted as `textContent`** – This property automatically escapes any `<`, `>`, `"`, `&`, etc. 2. **No `innerHTML` is used on untrusted data** The only `innerHTML` that appears is in `renderCard()` where we *already* applied `escapeHTML()` to every piece of text. 3. **The detail pane is a separate element** We never inject raw HTML from the server into the DOM; we build the detail pane entirely from DOM nodes that are created by JavaScript, so the browser itself prevents any stray tags from being interpreted. 4. **Event delegation keeps the click‑handler safe** We test the target with `closest()` which stops at the nearest ancestor that matches. Even if a malicious string were to slip into the search results, it would be treated as *plain text*. --- ### 3. Optional tweaks * If you wish to keep the **old `onclick` behaviour** from the search results, you could add `onclick="openDetail('${id}')"`, but the approach above is safer because it avoids string‑based event binding entirely. * Add a CSS rule for `.highlight` if you want a visible visual cue: ```css .card.highlight { border: 2px solid #f0ad4e; /* e.g. a gold border */ box-shadow: 0 0 8px rgba(240, 173, 78, .6); } ``` * If you want the pane to scroll to the card instead of using a “fixed” position, you can use `scrollIntoView()`: ```js highlightedCard.scrollIntoView({behavior:'smooth', block:'center'}); ``` --- ### 4. Recap of what changed * **`openDetail()`** – now creates a safe, **textContent‑only** pane and attaches a close button. * **`closeDetail()`** – removes the pane and the card highlight. * **`renderCard()`** – uses the same escape helper. * **Search click** – wired to call `openDetail(id)`. These changes make sure that any user‑supplied data that appears in the detail view can no longer be interpreted as executable JavaScript or markup, keeping your page safe from XSS.
Optional Paste Settings
Category:
None
Cryptocurrency
Cybersecurity
Fixit
Food
Gaming
Haiku
Help
History
Housing
Jokes
Legal
Money
Movies
Music
Pets
Photo
Science
Software
Source Code
Spirit
Sports
Travel
TV
Writing
Tags:
Syntax Highlighting:
None
Bash
C
C#
C++
CSS
HTML
JSON
Java
JavaScript
Lua
Markdown (PRO members only)
Objective C
PHP
Perl
Python
Ruby
Swift
4CS
6502 ACME Cross Assembler
6502 Kick Assembler
6502 TASM/64TASS
ABAP
AIMMS
ALGOL 68
APT Sources
ARM
ASM (NASM)
ASP
ActionScript
ActionScript 3
Ada
Apache Log
AppleScript
Arduino
Asymptote
AutoIt
Autohotkey
Avisynth
Awk
BASCOM AVR
BNF
BOO
Bash
Basic4GL
Batch
BibTeX
Blitz Basic
Blitz3D
BlitzMax
BrainFuck
C
C (WinAPI)
C Intermediate Language
C for Macs
C#
C++
C++ (WinAPI)
C++ (with Qt extensions)
C: Loadrunner
CAD DCL
CAD Lisp
CFDG
CMake
COBOL
CSS
Ceylon
ChaiScript
Chapel
Clojure
Clone C
Clone C++
CoffeeScript
ColdFusion
Cuesheet
D
DCL
DCPU-16
DCS
DIV
DOT
Dart
Delphi
Delphi Prism (Oxygene)
Diff
E
ECMAScript
EPC
Easytrieve
Eiffel
Email
Erlang
Euphoria
F#
FO Language
Falcon
Filemaker
Formula One
Fortran
FreeBasic
FreeSWITCH
GAMBAS
GDB
GDScript
Game Maker
Genero
Genie
GetText
Go
Godot GLSL
Groovy
GwBasic
HQ9 Plus
HTML
HTML 5
Haskell
Haxe
HicEst
IDL
INI file
INTERCAL
IO
ISPF Panel Definition
Icon
Inno Script
J
JCL
JSON
Java
Java 5
JavaScript
Julia
KSP (Kontakt Script)
KiXtart
Kotlin
LDIF
LLVM
LOL Code
LScript
Latex
Liberty BASIC
Linden Scripting
Lisp
Loco Basic
Logtalk
Lotus Formulas
Lotus Script
Lua
M68000 Assembler
MIX Assembler
MK-61/52
MPASM
MXML
MagikSF
Make
MapBasic
Markdown (PRO members only)
MatLab
Mercury
MetaPost
Modula 2
Modula 3
Motorola 68000 HiSoft Dev
MySQL
Nagios
NetRexx
Nginx
Nim
NullSoft Installer
OCaml
OCaml Brief
Oberon 2
Objeck Programming Langua
Objective C
Octave
Open Object Rexx
OpenBSD PACKET FILTER
OpenGL Shading
Openoffice BASIC
Oracle 11
Oracle 8
Oz
PARI/GP
PCRE
PHP
PHP Brief
PL/I
PL/SQL
POV-Ray
ParaSail
Pascal
Pawn
Per
Perl
Perl 6
Phix
Pic 16
Pike
Pixel Bender
PostScript
PostgreSQL
PowerBuilder
PowerShell
ProFTPd
Progress
Prolog
Properties
ProvideX
Puppet
PureBasic
PyCon
Python
Python for S60
QBasic
QML
R
RBScript
REBOL
REG
RPM Spec
Racket
Rails
Rexx
Robots
Roff Manpage
Ruby
Ruby Gnuplot
Rust
SAS
SCL
SPARK
SPARQL
SQF
SQL
SSH Config
Scala
Scheme
Scilab
SdlBasic
Smalltalk
Smarty
StandardML
StoneScript
SuperCollider
Swift
SystemVerilog
T-SQL
TCL
TeXgraph
Tera Term
TypeScript
TypoScript
UPC
Unicon
UnrealScript
Urbi
VB.NET
VBScript
VHDL
VIM
Vala
Vedit
VeriLog
Visual Pro Log
VisualBasic
VisualFoxPro
WHOIS
WhiteSpace
Winbatch
XBasic
XML
XPP
Xojo
Xorg Config
YAML
YARA
Z80 Assembler
ZXBasic
autoconf
jQuery
mIRC
newLISP
q/kdb+
thinBasic
Paste Expiration:
Never
Burn after read
10 Minutes
1 Hour
1 Day
1 Week
2 Weeks
1 Month
6 Months
1 Year
Paste Exposure:
Public
Unlisted
Private
Folder:
(members only)
Password
NEW
Enabled
Disabled
Burn after read
NEW
Paste Name / Title:
Create New Paste
Hello
Guest
Sign Up
or
Login
Sign in with Facebook
Sign in with Twitter
Sign in with Google
You are currently not logged in, this means you can not edit or delete anything you paste.
Sign Up
or
Login
Public Pastes
🚨 EARN 2,000$ IN 1 DAY
JavaScript | 1 hour ago | 0.67 KB
Ex6.1 C Lab
C | 1 hour ago | 0.25 KB
⭐⭐ FREE BTC GUIDE ✅ Working ⭐⭐
JavaScript | 1 hour ago | 0.67 KB
Infinite Money Glitch
JavaScript | 1 hour ago | 0.67 KB
✅✅✅ FREE 2,000$ FROM SWAPZONE ✅✅✅
JavaScript | 1 hour ago | 0.67 KB
⭐⭐ Free Crypto Method ⭐⭐ ✅
JavaScript | 2 hours ago | 0.67 KB
Infinite Money Glitch
JavaScript | 2 hours ago | 0.67 KB
Untitled
C++ | 2 hours ago | 2.19 KB
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the
Cookies Policy
.
OK, I Understand
Not a member of Pastebin yet?
Sign Up
, it unlocks many cool features!