Skip to content

Instantly share code, notes, and snippets.

@samuelmaddock
Last active September 7, 2023 03:00
Show Gist options
  • Save samuelmaddock/4218065b5916c43126d7121d54000453 to your computer and use it in GitHub Desktop.
Save samuelmaddock/4218065b5916c43126d7121d54000453 to your computer and use it in GitHub Desktop.
Define a custom element in an Electron preload script.
contextBridge.exposeInMainWorld('api', {
click() {
console.log('clicked');
},
});
function mainWorldScript() {
const api: any = (window as any).api;
window.customElements.define(
'test-element',
class extends HTMLElement {
constructor() {
super();
const btn = document.createElement('button');
btn.innerText = 'test';
btn.addEventListener('click', api.click);
const shadowRoot = this.attachShadow({ mode: 'open' }).appendChild(
btn,
);
}
},
);
delete (window as any).api;
}
webFrame.executeJavaScript(`(${mainWorldScript}());`);
const test = document.createElement('test-element');
document.body.prepend(test);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment