Electron App - How do i open link in browser?

Viewed 48

im trying to open a link in a new browser window using a Electron App.

const test = () => {
  const shell = window.require('electron').shell;
  shell.openExternal("https://google.com");
}

When i do this, i get error "window.require is not a function"

I have ofcourse made my research on this, and found several "fixes" but none has worked for me. I have edited my webpack.config.js to this:

module.exports = {
    configureWebpack: {
      externals: {
        './cptable': 'var cptable'
      },
      resolve: {
        fallback: {
          'fs': false,
          'crypto': false,
          'path': false,
        }
      }
    },
  }

I have also made sure nodeIntegration enabled like so:

const mainWindow = new BrowserWindow({
        width: 1280,
        height: 720,
        webPreferences: {
          nodeIntegration: true
        },
        autoHideMenuBar: true,
        resizable: false,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })
    ```

still no success. any idea?
1 Answers

renderer.js - from your renderer send request.

const response = await window.electronAPI.openLinkPlease() 

preload.js - you have this middleware where your request will receive to send to electron.

process.once("loaded", () => {
  contextBridge.exposeInMainWorld('electronAPI', {
      openLinkPlease: () => ipcRenderer.invoke('openLinkPlease'),
  })
});

electron.js - here you will get your request to open and electron will open this url in your default browser. First add at the very beginning const {shell} = require("electron"); to add shell capabilities and than after

            preload: path.join(__dirname, 'preload.js'),
    },
});

add

ipcMain.handle('openLinkPlease', () => {
    shell.openExternal("https://google.com");
})

This is the screen how it works from my application This is the screen how it works from my application

Related