Search code examples
node.jsreactjselectronreact-router-domelectron-react-boilerplate

How to load a URL into a BrowserView in an Electron React Boilerplate app that uses MemoryRouter?


I am building an Electron app using Electron React Boilerplate. ERB uses MemoryRouter from react-router-dom. The problem I'm facing is that I want to load a URL into a BrowserView inside a BrowserWindow. However, I think you cannot access a page/component via a URL like with BrowserRouter and React, MemoryRouter keeps the URL in memory.

mainWindow = new BrowserWindow({
    show: false,
    width: 1024,
    height: 728,
    minWidth: 436,
    minHeight: 147,
    icon: getAssetPath('icon.png'),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
    },
    frame: false,
  });

  mainWindow.loadURL(resolveHtmlPath('index.html'));
let browserView2 = new BrowserView({
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
    },
  });

  browserView2.setBounds({ x: 25, y: 100, width: 1024, height: 728 });
  browserView2.setAutoResize({
    width: true,
    height: true,
    horizontal: true,
    vertical: true,
  });

  // I want to load a page from React into the BrowserView
  browserView2.webContents.loadURL('http://localhost:1212/desired-component');

  // However, I can load an HTML file into the BrowserView like this
  // browserView2.webContents.loadURL(
  //   `file://${path.resolve(__dirname, '../renderer/', 'desired-component.html')}`
  // );

  mainWindow?.setBrowserView(browserView2);

Solution

  • please try to replace MemoryRouter with BrowserRouter

    import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
    
    const Hello = () => {
      return <div>hello...</div>;
    };
    const World = () => {
      return <div>world...</div>;
    };
    
    export default function App() {
      return (
        <Router>
          <Routes>
            <Route path="/" element={<Hello />} />
            <Route path="/world" element={<World />} />
          </Routes>
        </Router>
      );
    }
    

    then try to load the page into browserView:

    browserView.webContents.loadURL('http://localhost:1212/world');