Last active
September 7, 2023 03:00
-
-
Save samuelmaddock/4218065b5916c43126d7121d54000453 to your computer and use it in GitHub Desktop.
Define a custom element in an Electron preload script.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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