by jitl · 2y ago · 0 comments
This works because function.toString() in modern runtimes gives you back fully parse-able input source.
You need to make sure you don’t reference anything outside the function, but it’s generally nicer overall than JS-in-string.
Then you treat it as an IIFE. Example:
function globalJS() { document.write('hi') }
const html = `<script>(${globalJS})()</script>`
I use this technique for calling AppleScript-flavored-JS from NodeJS too.Overall a nice technique!
TIL - that is good to know. I'll probably leave the post as-is but I will use that in the future.