1

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);
quachhengtony
  • 125
  • 4
  • 17

1 Answers1

0

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');
kevin wang
  • 181
  • 5
  • This fixes my problem. But I thought you can't use BrowserRouter with Electron so It never crossed my mind that I should just change it to BrowserRouter, every post is about using HashRouter and MemoryRouter with Electron, etc, but thanks. – quachhengtony Jan 07 '22 at 01:25
  • I'm literally loading in `mainWindow.loadURL(resolveHtmlPath('anything'));` as virtually any string and it's _still_ loading in my App.ts as normal why is this? – KylianMbappe Jan 06 '23 at 19:50