Skip to content

Commit

Permalink
feat(eventhandler): support document, form, and this scope
Browse files Browse the repository at this point in the history
  • Loading branch information
clshortfuse committed Nov 8, 2024
1 parent 94c2190 commit a88c1f3
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions core/customTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,26 @@ export const EVENT_HANDLER_TYPE = {
this[name] = null;
return;
}
// Assign to temp element, allow it to parse and then copy result.
// Let browser parse instead of using eval()
// CSP Violations will be thrown by browser on failure and result in `null`
const button = document.createElement('button');
button.setAttribute('onclick', newValue);
const fn = button.onclick;
button.remove();
let fn;
try {
// Use eval to include scope
// https://blog.ltgt.net/html-event-handlers/
const scopedCode = 'with(this.ownerDocument ?? document){'
+ 'with(this.form ?? {}){'
+ `with(this){${newValue}}`
+ '}'
+ '}';
// eslint-disable-next-line no-new-func
fn = new Function(`return function ${name}(event){${scopedCode}}`)();
} catch {
// Assign to temp element, allow it to parse and then copy result.
// Let browser parse instead of using eval()
// CSP Violations will be thrown by browser on failure and result in `null`
const button = (this.ownerDocument ?? document).createElement('button');
button.setAttribute('onclick', newValue);
fn = button.onclick;
}

this[name] = fn;
},
propChangedCallback(name, oldValue, newValue) {
Expand Down

0 comments on commit a88c1f3

Please sign in to comment.