Skip to content

Instantly share code, notes, and snippets.

@JamoCA
Last active September 18, 2024 22:28
Show Gist options
  • Save JamoCA/0774f707e8b18b61bc95b5f2c39b1f9f to your computer and use it in GitHub Desktop.
Save JamoCA/0774f707e8b18b61bc95b5f2c39b1f9f to your computer and use it in GitHub Desktop.
createShadowHtml UDF - Using ColdFusion to generate HTML to create & populate a shadow DOM. #cfml
<!--- createShadowHtml UDF - Using ColdFusion to generate HTML to create & populate a shadow DOM.
NOTE: This approach requires using absolute HREF/SRC references for links and static resources.
GIST: https://gist.github.com/JamoCA/0774f707e8b18b61bc95b5f2c39b1f9f
BLOG: https://dev.to/gamesover/embed-a-full-html-document-inline-using-shadow-dom-5d5d
TWEET: https://x.com/gamesover/status/1836493265186754801
--->
<cfscript>
string function createShadowHtml(required string html, string id="", boolean enableLinks=true, string placeholder="Previewable content will be displayed here...") hint="I generate a shadow DOM on-the-fly to preview HTML/CSS (No JS)" {
local.newLine = createobject("java", "java.lang.System").getProperty("line.separator");
local.id = (isvalid("variablename", arguments.id)) ? arguments.id : "shadow" & randrange(10000,99999,"SHA1PRNG");
local.html = ["<div id=""#local.id#"">#trim(arguments.placeholder)#</div>"];
arrayappend(local.html, "<script>");
arrayappend(local.html, "var pane_#local.id# = document.querySelector('###local.id#');");
arrayappend(local.html, "var shadow_#local.id# = pane_#local.id#.attachShadow({mode: 'open'});");
arrayappend(local.html, "var html_#local.id# = #serializejson({"html": trim(arguments.html)})#");
arrayappend(local.html, "shadow_#local.id#.innerHTML = html_#local.id#.html;");
if (arguments.enableLinks){
arrayappend(local.html, "shadowLinks_#local.id# = shadow_#local.id#.querySelectorAll('a');");
arrayappend(local.html, "for (link of shadowLinks_#local.id#){");
arrayappend(local.html, "link.addEventListener('click', function(e){");
arrayappend(local.html, "e.preventDefault();");
arrayappend(local.html, "alert('Sorry. Links aren\'t enabled in preview mode.');");
arrayappend(local.html, "});");
arrayappend(local.html, "}");
}
arrayappend(local.html, "</script>");
return arraytolist(local.html, local.newLine);
}
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment