SeoBomi
SeoBomi

Reputation: 39

Electron multi window in typescript

I am using react + typescript + electron. I want to display an HTML element to the new electron window.

Electron only can open a new window by URL. So I found a solution at here

This code is written by javascript, and I am a beginner of javascript and typescript.

Error is occurred at

let view = ViewManager.Views()[name];

Element implicitly has an 'any' type because the expression of type 'any' can't be used to index type 'Element'.

Also, I cannot understand this code. Could you explain to me this code or change this js code to typescript?

Upvotes: 0

Views: 1017

Answers (1)

Paul Rumkin
Paul Rumkin

Reputation: 6873

To create new window you should use BrowserWindow class. Rendering custom HTML is non-trivial task. You have several options:

  1. Pass HTML into new window with URL params like: file:///your-app-path/view.html?html=<h1>Custom HTML</h1>. And realize you logic of HTML rendering on your own in /your-app-path/view.html.

  2. Deliver HTML with inter process communication (IPC) between the main process and the window using WebContents and ipcRenderer.

  3. Use custom protocol to deliver HTML to the window using dynamic page creation. This feature is called "protocol handling". This is a description of protocol.registerBufferProtocol().

    Here is a working example:

     const {app, BrowserWindow, protocol} = require('electron')
    
     app.whenReady()
     .then(() => {
       let id = 0
       const pages = new Map()
    
       function openNewWindow(html) {
         const winId = ++id // create new window id
         const hostname = `x${winId}` // create correct hostname
    
         pages.set(hostname, html)
    
         const win = new BrowserWindow()
         win.loadURL(`my-protocol://${hostname}`)
         win.on('closed', () => {
           pages.delete(hostname)
         })
       }
    
       protocol.registerBufferProtocol('my-protocol', (request, callback) => {
         const {hostname} = new URL(request.url)
         const body = pages.get(hostname) || '<html><body><h1>Nothing found</h1></body></html>'
         callback({
           mimeType: 'text/html',
           data: Buffer.from(body),
         })
       }, (error) => {
         if (error) {
           console.error('Failed to register protocol')
         }
       })
    
       openNewWindow(`
         <html>
           <head><title>Test</title></head>
           <body>
             <h1>It works</h1>
           </body>
         </html>
       `)
     })
    

Upvotes: 2

Related Questions