VN-Designer Developer Documentation
07

Scripts in blocks and themes

How a block ships JavaScript, how it detects the editor, what the editor does with scripts, how cookie consent and privacy are connected, which libraries are shipped under vendor/, and which pitfalls exist.

Overview#

A block ships JavaScript as an inline <script> in the template. There is no separate JS file per block or theme. The script usually sits at the end of the root element and is delivered with the template: in the editor, in the preview and in the export.

PlaceDoes the script run?How
Export (publish/), browser preview and live previewyes, normallyThe page is served through a local server (preview-server.cjs); the script runs as on the real page
Editor (canvas)yes, shieldedsrc/editor-scripts.js runs inline scripts after every render using stand-ins (see Behavior in the editor); can be switched off
Code editornoOnly the template HTML is shown there

Order of an exported page (from buildExportHtml):

  1. <head>: Bootstrap CSS, Bootstrap Icons CSS, the CSS files of the runtime libraries in use, style.css.
  2. <body>: the HTML code of all blocks on the page in order, each with its inline scripts.
  3. After that vendor/bootstrap.bundle.min.js, then the scripts of the runtime libraries (lightbox, cookie consent, popup, CMS, video …), then the user's scripts.

Scripts in blocks#

Inline script in the template#

Syntax

html
<section class="va va-inhalt" group="Content">
  <vn-parameters> … </vn-parameters>
  <div class="va-in" data-anim="{{anim}}"> … </div>
  <script>(function(){
    [].forEach.call(document.querySelectorAll(".va-in"), function(R){
      if (R.__vaInit) return; R.__vaInit = 1;       /* once per element */
      if (R.closest("#canvas")) return;              /* do nothing in the editor */
      /* … effect … */
    });
  })();</script>
</section>

(Pattern from gallery-content/vn-bloecke/src/artikel/inhalt/template.html; there the flag is a data-va-init attribute, the JS property is recommended)

RuleDescription
LocationInside the root element, usually as the last child
KindOnly <script> without src and without a foreign type is run in the editor (type empty, text/javascript, application/javascript, module)
Foreign typestype="text/x-vn-php" (protected PHP code) and JSON data blocks are not run by the editor and not touched by cookie consent
Placeholders{{…}} is replaced in the whole template, including the script text. A double opening brace in the script (for example an object literal inside an object literal, {{a:1}}) is evaluated as an expression: write { { or avoid the sequence
Conditionsvn-if on the <script> is possible; if it is dropped, the script is missing
External files<script src="…"> runs in the export, not in the editor. Avoid third-party servers (CDN) for privacy reasons

One-time initialization#

The script should find all elements of its block in the document and initialize each of them only once. Set the flag as a JavaScript property on the element, not as a data- attribute.

Syntax

js
(function () {
  var roots = document.querySelectorAll(".mein-block");
  Array.prototype.forEach.call(roots, function (box) {
    if (box.vnInit) return;     // already done (property, not attribute)
    box.vnInit = 1;
    if (box.closest("#canvas")) return;
    // … initialization …
  });
})();
FlagSuitabilityReason
JS property (box.vnInit = 1)recommendedBelongs to the element, never in the HTML, never in the saved template, never in the export
data-… attributeavoidThe script runs over all elements of the page; an older block script set the attribute on elements of new blocks, and these were then never initialized. In addition, an attribute ends up in the DOM that may be baked later
Global variable (window.fertig = true)only for shared helper functionsIn the editor, window.… is valid only for one render pass (see below); on the real page it stays set for all blocks

Shared namespace for several instances (from the “Video embed” block):

js
(function () {
  var V = window.vfvd = window.vfvd || {};   // create once, reuse later
  if (!V.parse) {
    V.ed = function (e) { return !!(e && e.closest && e.closest("#canvas")); };
    V.parse = function (raw) { /* … */ };
  }
  // … per instance …
})();

Order and waiting#

When the block script runs (parsing of <body>), the following do not exist yet: window.bootstrap, window.vnCookieConsent, window.VNPopup, elements further down the page. Wait for DOMContentLoaded or load.

js
function late(fn) {
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", fn);
  else fn();
}
late(function () {
  var cc = window.vnCookieConsent;          // available now (if cookie consent is switched on)
  var BS = window.bootstrap;                // Bootstrap 5.0.1
});

In the editor, DOMContentLoaded and load have already passed; the editor calls such callbacks immediately (time-shifted) and reports document.readyState === "complete". The same notation therefore works in both places.

Marker data-vn-editor-only#

Elements with data-vn-editor-only are stand-ins for the editor. The export removes them (publish.js: container.querySelectorAll('[data-vn-editor-only]').forEach(remove)). Typical uses: hint lines (“No video chosen yet”), sample content for PHP output that does not run in the editor.

Syntax

html
<div class="vn-bgvid-empty" data-vn-editor-only vn-if="!videoFile &amp;&amp; !videoUrl">
  Noch kein Video gewählt — im Eigenschaften-Panel unter „Video“ eine Datei wählen.
</div>
AttributeValueMeaning
data-vn-editor-onlyswitchThe element appears in the editor and in the block preview, not in the export

Editor detection#

Detection with el.closest('#canvas')#

The only reliable detection is the position in the canvas: The canvas is an element with the ID canvas in the same document as the program (no iframe). A block element in the editor has #canvas as an ancestor, in the export and in the preview it does not.

Syntax

js
var inEditor = !!el.closest("#canvas");
if (inEditor) return;        // or only skip the effect but still set the content
Value of el.closest("#canvas")Meaning
ElementEditor (canvas)
nullExport, preview or live preview

Editor, preview and export compared#

FeatureEditor (canvas)Preview and live previewExport
Block scriptsshielded, after every rendernormalnormal
el.closest("#canvas")elementnullnull
window.bootstrappresentpresent (after the block scripts)present (after the block scripts)
jQuerynono (only in Bootstrap theme mode)no (only in Bootstrap theme mode)
Runtime libraries (lightbox, consent, popup …)no (exception: VN Submenu)yes, as in the exportyes, if used
data-vn-editor-only elementsvisibleremovedremoved
PHPdoes not run (stand-ins)runs through the local serverruns on your server
Mail sending—to a local mail catcher (.eml files)through your SMTP server

What is not suitable for detection#

Verified in a running instance:

MeansResult in the editorConsequence
document.documentElement.classList.contains("is-builder")falseThe program never sets the class; it deliberately does not set it globally, so as not to activate .is-builder rules for every imported block
document.body.classList.contains("is-builder")falseas above (only the lightbox respects it)
document.currentScriptnullThe editor runs scripts through new Function; a script that looks up its block through currentScript needs a fallback (document.querySelector(…))
window.self !== window.topfalseThere is no iframe

Behavior in the editor#

Stand-ins instead of free running#

The canvas is part of the program window. A block script therefore does not run freely but in a function that overlays the global names with stand-ins (new Function('document','window','location','setTimeout',…)). As a result, a script can neither redirect the program nor keep running after the next render.

Access in the scriptBehavior in the editor
setTimeout, setInterval, requestAnimationFrameCallbacks run only as long as the render pass in which the script started is current; every new render ends all chains of the old one
document.addEventListener('DOMContentLoaded'/'load'/'readystatechange', fn) and the same on windowCallback runs immediately (time-shifted, setTimeout 0)
window.onload = fnis run immediately as a callback
document.readyStatealways complete
document.write, document.writelndoes nothing
location.assign, .replace, .reload; location.href = …does nothing; reading works
alert, confirm, promptdo nothing (confirm returns false, prompt returns null)
other document/window callsnormal (bound to the real object)
this, self, globalThis, window.windowthe stand-in

Errors in the script are only written to the console (Block-Skript im Editor nicht ausgeführt: …) and do not disturb the canvas.

Re-rendering and timers#

On every render of the canvas (renderCanvasNow), the program first calls stopBlockScripts() (timers/chains of the previous pass end), rebuilds all blocks and afterwards, when everything is in the document and the CSS is set, runs the inline scripts of every block. Almost every change in the panel triggers a render: the script therefore often runs again, on fresh elements.

window properties apply for one pass only#

Whatever a block script attaches to window (window.initialisiert = true, window.vfvd = {…}) ends up in a store that is discarded with the next render. Otherwise the guard if (!window.fertig) { window.fertig = true; … } would stay set, and the script would never start again after the first re-render. On the real page this limitation does not exist.

Verified: a script that sets window.__leak = 5 leaves nothing on the real window; after stopBlockScripts(), typeof window.initFlag is undefined again.

Switching off#

The page settings contain the switch for block scripts in the editor (siteSettings.editorScripts, on by default). Off: block scripts never run in the editor; blocks that create their visible content only through JavaScript then show only the initial state.

Rules for scripts in the editor#

RuleReason
Do not move, hide or swap DOM in the editor (no-op): carousel rebuild, reveal with opacity:0, collapsing, cloningOtherwise the content disappears or can no longer be clicked
Still set a parameter-dependent initial state (first word, counter end value, date) and only then stopPutting if (closest('#canvas')) return; at the start means changes in the panel are not shown in the editor (symptom “typewriter does not show the new word”)
Never rewrite the content of a text field (no letter <span>s, no innerHTML on data-vn-text-id elements)On the next typing, the program saves the current innerHTML of the field as text (input event); an intermediate state of the effect would become the saved text
No endless runners that do not end themselvesTimers are aborted, but event listeners on document/window stay until reload

Text animations at runtime#

Effects that split or rewrite text (fading in letters one by one, counting up a counter, typewriter, changing words) happen at runtime in the browser. The saved HTML always contains the complete, static text. This is how search engines, the translator, the CMS and text editing find it.

RuleDescription
SourceThe real text is in the template (or in a data- attribute such as data-words)
EffectThe script splits or replaces the content only when the page loads
EditorNo effect, only the initial state (see Rules)
Without JavaScriptThe text stays fully readable
With “reduced motion”The effect is dropped (next section)

For simple animations without your own script there is the tool VN Animation (Animations): It sets data-vn-anim attributes and delivers keyframes and a small observer script.

Reduced motion#

Everything that moves must respect the system setting “Reduce motion”: through CSS and through script.

Syntax

js
var RM = !!(window.matchMedia && matchMedia("(prefers-reduced-motion: reduce)").matches);
if (!RM && "IntersectionObserver" in window) { /* start fade-in effect */ }
css
@media (prefers-reduced-motion: reduce) {
  .mein-block .effekt { animation: none !important; transition: none !important; }
}
ComponentBehavior with “reduced motion”
VN Animation (export rules)[data-vn-anim] { animation: none !important }
VN background video (vendor/vn-bgvideo)Video is not started; poster image stays
VN Popupcloses without animation
VN Gallery (carousel)scrolls without smooth scrolling
Smooth scrolling to anchors (vn-bgvid-scroll)jumps instead of gliding

If VN Cookie Consent is switched on in the project settings, the export blocks known third-party content until the matching category has been accepted. Third-party content (maps, videos, tracking) then loads only after consent or a click.

gateThirdPartyEmbeds (export, on every block) and gateRawScriptText (global HTML insertions) detect:

ContentDetectionCategory
Google Maps (<iframe src>)google.<tld>/maps, maps.google., goo.gl/mapsfunctional
YouTube embedyoutube.com/embed/…, youtube.com/v/…, also youtube-nocookie.com (the IP address goes to the provider as soon as the player loads)marketing
Vimeo embed (from version 1.3.100)player.vimeo.com/video/… (the page address vimeo.com/<no.> is not an embed and is not detected)marketing
Google Analytics / Tag Manager<script src> with googletagmanager.com, google-analytics.com; inline code with gtag(, googletagmanager, GoogleAnalyticsObjectstatistics
Facebook Pixelconnect.facebook.net, facebook.com/tr; inline fbq(marketing

For everything else, mark the element yourself:

html
<iframe src="https://example.com/widget" data-vn-consent-category="functional"></iframe>
<script src="https://example.com/stats.js" data-vn-consent-category="statistics"></script>
AttributeValuesMeaning
data-vn-consent-categoryfunctional, statistics, marketingThe element is blocked until the category is accepted; works regardless of the domain

What the export makes of it

html

<div class="vn-cc-gate" data-vn-cc-category="marketing" style="width:560px;height:315px">
  <iframe data-vn-cc-src="https://www.youtube-nocookie.com/embed/ID" …></iframe>
  <div class="vn-cc-gate-overlay">
    <p class="vn-cc-gate-text" data-vn-cc-category="marketing"></p>
    <div class="vn-cc-gate-buttons"><button type="button" class="vn-cc-gate-accept"></button><button type="button" class="vn-cc-gate-settings"></button></div>
  </div>
</div>

<script type="text/plain" data-vn-cc-category="statistics" data-vn-cc-src="https://example.com/stats.js"></script>
MarkerMeaning
data-vn-cc-srcThe original src; becomes src again after consent
type="text/plain" + data-vn-cc-categoryBlocked script; after consent a real <script> is inserted, type and data-vn-cc* are dropped, other attributes stay
.vn-cc-gateWrapper with overlay (“Load content”, “Settings”); “Load content” releases only this one embed

Blocks that load third-party material through JavaScript (click on a preview image, map) build the gate themselves and use the same interface. This keeps the block independent of whether consent is switched on.

Interface window.vnCookieConsent (exists only after DOMContentLoaded; only if cookie consent is switched on):

CallReturn valueMeaning
getConsent(){ necessary: true, functional, statistics, marketing } (boolean values)State of the consent; without a decision everything is false
openSettings()—Opens the settings window
labelGates()—Relabels all .vn-cc-gate-text, .vn-cc-gate-accept and .vn-cc-gate-settings (call it after inserting your own)

Event vn-cc-activated is fired on the wrapper as soon as it has been released (click on “Load content” or consent to the category). React to it in order to load.

Pattern (abridged from gallery-content/vn-bloecke/src/video/embed/template.html):

js
var c = window.vnCookieConsent && window.vnCookieConsent.getConsent ? window.vnCookieConsent : null;
function ask(host, go) {
  if (!c || c.getConsent().marketing) { go(); return; }          // without consent, or already allowed
  host.classList.add("vn-cc-gate");
  host.setAttribute("data-vn-cc-category", "marketing");
  var o = document.createElement("div");
  o.className = "vn-cc-gate-overlay";
  o.innerHTML = '<p class="vn-cc-gate-text" data-vn-cc-category="marketing"></p>'
    + '<div class="vn-cc-gate-buttons"><button type="button" class="vn-cc-gate-accept"></button>'
    + '<button type="button" class="vn-cc-gate-settings"></button></div>';
  host.appendChild(o);
  if (c.labelGates) c.labelGates();
  host.addEventListener("vn-cc-activated", function f() {
    host.removeEventListener("vn-cc-activated", f);
    o.remove(); host.classList.remove("vn-cc-gate", "vn-cc-activated");
    go();
  });
}

From version 1.3.100, VN Cookie Consent fires the event vn-cc-consent on the document after every new choice by the visitor ("Save", "Accept all", "Necessary only"); event.detail is the new consent (the same object as getConsent()). It does not fire when the page loads with an already stored choice, and not when a single gate's "Load content" is clicked (that is what vn-cc-activated is for). A script that should load something only after consent therefore checks getConsent() at start and additionally listens for the event:

js
function ok() {
  var c = window.vnCookieConsent;
  return !c || !c.getConsent || !!c.getConsent().marketing;   // ohne Cookie-Consent auf der Seite: sofort
}
function start() { /* Fremdinhalt laden */ }
if (ok()) start();
else document.addEventListener("vn-cc-consent", function f() {
  if (!ok()) return;
  document.removeEventListener("vn-cc-consent", f);
  start();
});

This is how the background video (vendor/vn-bgvideo/vn-bgvideo.js) works: with cookie consent switched on, YouTube and Vimeo backgrounds load only after the visitor has agreed to "Marketing"; the fallback image stays in place until then (Video background).

YouTube and Vimeo only after a click#

The privacy principle: There is no connection to YouTube or Vimeo before the visitor becomes active. Two ways:

  1. Two-click solution in the block: First only a preview image with a play button (button with img); only the click creates the <iframe>. Example gallery-content/vn-bloecke/src/effekte/videoprivacy/template.html:
html
<div class="vf-vd" data-v="{{video}}">
  <div class="vf-vd-frame">
    <button class="vf-vd-poster" type="button" aria-label="Video abspielen">
      <img src="{{imgPoster}}" alt="Vorschaubild">
      <span class="vf-vd-label">Video abspielen</span>
    </button>
  </div>
</div>
<script>(function(){document.querySelectorAll(".vf-vd").forEach(function(b){if(b.dataset.vfInit)return;b.dataset.vfInit=1;
var fr=b.querySelector(".vf-vd-frame"),po=b.querySelector(".vf-vd-poster");if(!po)return;
po.addEventListener("click",function(){if(b.closest("#canvas"))return;
var raw=(b.dataset.v||"").trim(),id=raw,m=raw.match(/(?:v=|youtu\.be\/|embed\/|shorts\/|live\/)([A-Za-z0-9_-]{11})/);if(m)id=m[1];
if(!/^[A-Za-z0-9_-]{6,20}$/.test(id))return;
var f=document.createElement("iframe");f.src="https://www.youtube-nocookie.com/embed/"+id+"?autoplay=1&rel=0";f.title="Video";
f.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen";f.setAttribute("allowfullscreen","");f.setAttribute("referrerpolicy","strict-origin-when-cross-origin");
fr.appendChild(f);b.classList.add("is-playing");po.hidden=true})})})();</script>
  1. Embed with blocking: A normal <iframe> with an address; with consent switched on, the export blocks it automatically (Automatic blocking).

Text data in attributes: vnEnc#

In the template, a text from the panel must never appear raw in data-…="{{x}}": a quotation mark or {{ in the text breaks the markup. Use vnEnc(text) and decode in the script.

Syntax

html
<div class="mein-block" data-titel="{{vnEnc(titel)}}"></div>
js
var titel = decodeURIComponent(box.getAttribute("data-titel") || "");
Helper functionValid inMeaning
vnEnc(wert){{…}} and conditions in the templateencodeURIComponent(String(wert)); undefined/null gives ''
vnEmbed(adresse){{…}} in the templateYouTube/Vimeo address → embeddable address (youtube-nocookie.com/embed/… or player.vimeo.com/video/…); other addresses stay unchanged
{{vn-id}}Template (text, attributes, also in the script text)Block ID or anchor ID of the instance; unique IDs: id="{{vn-id}}-nav"

These three are helpers of the template expression, not global JavaScript functions: in the script itself (window.vnEnc) they do not exist (verified: typeof window.vnEnc === "undefined"). The expressions also run with access to the global standard objects (String, Number, Math, encodeURIComponent …).

Shipped libraries#

Everything third-party that a block needs must be shipped (no CDN calls, no web fonts). On export, the program copies only what the pages actually use. The following libraries are located under vendor/; the selection depends on traces in the finished HTML.

LibraryPurposeExport (condition)
Bootstrap 5.0.1 (CSS + bundle JS)Grid, helper classes, dropdown, collapse, tooltip, modalalways (bundle: window.bootstrap), except in Bootstrap theme mode
Bootstrap IconsIcon font bi bi-…always (vendor/bootstrap-icons/)
FlagsCountry flags (SVG, 4:3 and 1:1)as project files under assets/, only the ones used
jQuery 3.5.1Only for older Bootstrap 4 themes and their pluginsonly in theme mode (vendor/jquery.min.js)
VN LightboxZooming/panning of imagespage setting switched on
VN Cookie ConsentBanner, blocking, vnCookieConsentpage setting switched on
VN PopupPopup blockspage contains a popup
VN CMSEditing on the finished pagepage contains a CMS block
VN SubmenuMenu level that opens sidewaysli.vn-submenu in the HTML
VN TooltipTooltips on wordsspan.vn-tip in the HTML
VN VideoExtra functions for self-hosted videosvideo.vn-video-el in the HTML
VN Background videoBackground video (file, YouTube, Vimeo)data-bg-video with a value, or .vn-bgvid
VN TranslatorLive translationpage setting switched on
VN WhatsAppFloating contact buttonpage setting (with number)
VN Form (vn-sform), Form RendererForms, sendingform.vn-sform-form or Form Renderer block
VN PDF viewer (PDF.js 3.11.174)PDF and tablesblock with viewer address
VN Search, VN BlogPHP systemsthe respective blocks
jszip, less, CodeMirrorEditor onlynever in the export

The following entries describe the libraries that a block author uses or controls from within a block. Integration is always the same: do nothing (set a marker); the export inserts <link>/<script> itself.

Bootstrap 5.0.1 and Bootstrap Icons#

The bundle provides window.bootstrap (Collapse, Dropdown, Tooltip, Modal, Carousel …). It runs after the block scripts.

js
document.addEventListener("DOMContentLoaded", function () {
  var el = document.querySelector("#mein-id-modal");
  if (el && window.bootstrap) new bootstrap.Modal(el).show();
});
NoteDescription
AttributesBootstrap 5 names (data-bs-toggle, data-bs-target); the import supplements the Bootstrap 4 names (data-toggle, data-target, data-dismiss, data-ride, data-slide, data-slide-to, data-parent) with the 5 names (data-bs-…) when reading them in
EditorThe bundle is loaded in the editor (menus and dropdowns work); jQuery is not
Icons<i class="bi bi-NAME">; the icon list (2078 icons) is searched in the icon dialog

jQuery and theme plugins (Bootstrap theme mode)#

A project can run on the Bootstrap of a theme (for example Bootstrap 4.5; siteSettings.bootstrapMode = 'theme'). The export then loads this order instead of Bootstrap 5: jQuery (vendor/jquery.min.js, 3.5.1), Popper, the theme's Bootstrap JS, smooth scroll, the plugins of the blocks in use (with dependencies), and finally the theme script.

Which plugins a block wants is stated on the root element:

html
<section class="menu" plugins="DropDown, TouchSwipe"> … </section>
AttributeValueMeaning
pluginsList of plugin names (comma, case-insensitive)Theme mode only: loads these plugin folders of the theme (plugins/<name>/, .js only; for pairs the .min version)

Dependencies are built in (masonry needs imagesloaded; gallery needs imagesloaded and masonry). A parallax background marker in the markup triggers the parallax plugin. The script files are in the project under assets/theme-js/, so that the export works without the package.

VN Lightbox#

Site-wide zoomable and pannable images. The block only marks what should be zoomed; details and attributes: Lightbox.

html
<img class="vn-zoom" src="assets/images/foto.jpg" alt="Foto" data-vn-caption="Bildunterschrift">

Settings window, blocking, the configuration window.VN_COOKIE_CONFIG, the interface vnCookieConsent and the event vn-cc-consent. Link to reopen: <a href="#" data-vn-cookie-settings> (Cookie link). Categories: functional, statistics, marketing; consent is stored in localStorage.

VN Popup#

Window above the page; triggered by link, time, scrolling, leaving the page; interface VNPopup (Popup).

VN CMS#

Editing on the finished page (vendor/vn-cms, PHP). Markers and server folders: CMS.

VN Submenu#

Plain JS, inserts its CSS rules itself (<style data-vn-submenu>), sets window.__vnSubmenu. Markup: Submenu. It is also loaded in the editor (vendor/vn-submenu/vn-submenu.js in index.html).

VN Tooltip#

Activates span.vn-tip[data-bs-toggle="tooltip"] through the Bootstrap tooltip; without Bootstrap 5 the title hint remains. Markup: Tooltips.

VN Translator#

Language button for visitors; only exceptions are marked: Translator.

VN WhatsApp#

Floating contact button, purely through the page setting (window.VN_WHATSAPP_CONFIG: phone, message, side, bottomOffset, sideOffset, bubbleEnabled, bubbleTitle, bubbleText, bubbleDelay). A block has nothing to do with it; for a link to WhatsApp see Phone and WhatsApp.

VN Video, background video, forms, PDF, search, blog#

These libraries belong to finished blocks. Their markers and settings are described in the chapters Forms and Media.

LibraryPurposeHow a block uses it
VN Video (vendor/vn-video)Start/end time, speed, lazy loading, VN Playervideo.vn-video-el with data-… values (Self-hosted video)
VN Background video (vendor/vn-bgvideo)Video behind the contentdata-bg-video="<address>" or class vn-bgvid (Video background)
VN Form (vendor/vn-sform)Validating and sending static formsform.vn-sform-form (Forms)
Form Renderer (vendor/vn-formrender)Form from JSON, rules, PHP sendingsection.vn-formrender with .vnfr-data (Form Renderer)
VN PDF viewer (vendor/vn-pdf-viewer)PDF.js with searchiframe[data-vn-pdf-src] (PDF)
VN Search (vendor/vn-search)Full-text search (PHP)section.vn-search (Search)
VN Blog (vendor/vn-blog)Blog (PHP, SQLite)Include in the protected PHP script (Blog)

Pitfalls: script runs in the editor and destroys content#

All reports about scripts so far can be traced back to these classes:

PitfallEffectRemedy
Script rewrites the content of a data-vn-text-id elementOn typing, the intermediate state is saved; text “destroyed”Effects only outside the canvas; keep the text in the template static
if (closest('#canvas')) return; before setting the initial valuePanel changes are invisible in the editorSet the initial state, then stop
Script hides content (opacity:0, display:none, .reveal) and only shows it through an observerIn the editor only the background appearsHide only after the editor check
data-… init flagNew blocks are skipped by old scripts “as already done”JS property on the element
Fixed IDs / global stateSecond instance brokenClasses, {{vn-id}}, namespace
document.currentScript without a fallbacknull in the editordocument.querySelector(…) as a fallback
Check for is-builderEditor is never detectedclosest('#canvas')
Access to bootstrap/vnCookieConsent while parsingundefinedWait for DOMContentLoaded
jQuery assumednot present in the editor and the normal exportPlain JavaScript
window guard (window.fertig)reset per render in the editor, permanent on the real pageFlag on the element
<script type="module"> with a static importcannot be run in the editor (runs in new Function)Classic script
Raw text in data-x="{{x}}"Markup breaks on quotation marks or {{vnEnc(x) + decodeURIComponent
Own third-party addresses (CDN, fonts)Privacy, unusable offlineShip them or leave them out
Access to location to redirect in the editorno effect (intentional)only useful on the real page