electron icon indicating copy to clipboard operation
electron copied to clipboard

Unable to use 'remote' module

Open protozoo opened this issue 10 years ago • 18 comments

Hi,

I'm trying to use the remote module but I'm getting an error when running my app:

App threw an error when running [TypeError: Cannot read property 'BrowserWindow' of undefined]

Here's a simplified version of my code:

const remote = require('electron').remote;
const BrowserWindow = remote.BrowserWindow;
var win = new BrowserWindow({ width: 800, height: 600 });
win.loadURL('https://github.com');

Any idea what the problem can be?

Many thanks

protozoo avatar Dec 10 '15 09:12 protozoo

I suspect the first line should be: const remote = require('remote');

lee-dohm avatar Dec 10 '15 09:12 lee-dohm

Doing so throws this error:

Error: Cannot find module 'remote'

which makes sense, since 'remote' is supposed to be a module within Electron, as far as I understand. I tried running npm install --save remote but I guess that's a completely unrelated module, and the error I get when running my app again after installing that seems unrelated:

App threw an error when running [SyntaxError: Unexpected token >]

I'm just following this example: https://github.com/atom/electron/blob/master/docs/api/remote.md

Am I missing something?

Thanks!

protozoo avatar Dec 10 '15 09:12 protozoo

I guess they've changed the way to require remote. The blame information points to this change:

https://github.com/atom/electron/commit/eac2e7cc614d4e98e2828921f63d55f7b5e2c85c

Are you using v0.35.0 or above of Electron?

lee-dohm avatar Dec 10 '15 09:12 lee-dohm

Are you sure that you are using from the renderer process?

herrmannplatz avatar Dec 10 '15 09:12 herrmannplatz

@lee-dohm I'm running v0.33.8:

$ electron --version
v0.33.8

Here's my package.json relevant section:

(...)
  "dependencies": {
    "electron": "^0.4.1",
    (...)
  },
  "devDependencies": {
    "electron-packager": "^5.1.0",
    "electron-prebuilt": "^0.33.9",
    "electron-rebuild": "^1.0.0",
    (...)
  }
(...)

Not sure how to upgrade (if it applies).

@herrmannplatz Oops... nope, I was doing so in the main process... I now tried running var remote = require('electron').remote; in the console of the main window, and I just get undefined.

Thanks again

protozoo avatar Dec 10 '15 09:12 protozoo

Damn! sorry, please forget it, I now see remote.getGlobal() IS working. Thanks for your time.

protozoo avatar Dec 10 '15 09:12 protozoo

Hi @protozoo ,

I'm getting your same error (i.e. Module not found: Error: Cannot resolve module 'electron' ) when trying to load the remote module within the renderer.

As you did I'm using the method found in the API docs: const remote = require('electron').remote;

I see that in package.json you have "electron": "^0.4.1",. Isn't that a different package? Referring to the FAQ page seems like that might override Electron's built-in module.

So how did you solve the issue? Were you just requiring electron + remote from the main process, and move the assignment to the renderer?

Thanks in advance for any input!

miccferr avatar Feb 15 '16 00:02 miccferr

You should not use electron from npm. Also, in case you're using webpack, you'd probably get another errors about require, I think it is because Electron has it's own implementation to get its packages. If you get that problem use target : 'electron' in your webpack configuration. https://webpack.github.io/docs/configuration.html#target

renemonroy avatar Feb 15 '16 00:02 renemonroy

Aha, I think that Webpack was "the issue" then. Good call, thanks @renemonroy !

Also, can you elaborate why I should not use electron from npm? You mean it's not good practice to use npm scripts like:

  "scripts": {
    "start": "./node_modules/.bin/electron main.js"  
  }

miccferr avatar Feb 15 '16 00:02 miccferr

@miccferr I was talking about the package, electron in npm is not related to Atom Electron, you need to use one of these ways:

# Install the `electron` command globally in your $PATH
npm install electron-prebuilt -g

# Install as a development dependency
npm install electron-prebuilt --save-dev

Your start script is the right way.

renemonroy avatar Feb 15 '16 04:02 renemonroy

I'm using electron-prebuilt version 0.36.8 and I got this error message: App threw an error when running [TypeError: Cannot read property 'BrowserWindow' of undefined]. Below is my code snippet:

const electron = require('electron');
const remote = electron.remote;
const BrowserWindow = remote.BrowserWindow;

Inspection on electron variable shows the following:

{ hideInternalModules: [Function],
  clipboard: [Getter],
  crashReporter: [Getter],
  deprecations: [Getter],
  nativeImage: [Getter],
  shell: [Getter],
  app: [Getter],
  autoUpdater: [Getter],
  BrowserWindow: [Getter],
  contentTracing: [Getter],
  dialog: [Getter],
  ipcMain: [Getter],
  globalShortcut: [Getter],
  Menu: [Getter],
  MenuItem: [Getter],
  powerMonitor: [Getter],
  powerSaveBlocker: [Getter],
  protocol: [Getter],
  screen: [Getter],
  session: [Getter],
  Tray: [Getter] }

I tried the methods above and none worked for me.

Any help is appreciated!!

missingtrailingcomma avatar Feb 20 '16 04:02 missingtrailingcomma

@tinirlove The remote module is only available in the renderer process, you are attempting to access it in the browser/main process.

enlight avatar Feb 20 '16 04:02 enlight

@tinirlove Did you find a solution for your problem? I got the same error. I also changed the webpack target to 'electron'.

I get this error:

ERROR in ./~/superagent/package.json
Module parse failed: /Users/roman/src/private/parrot/node_modules/superagent/package.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
|   "_args": [
|     [
|       "superagent",
 @ ./~/superagent/lib/node/index.js 25:10-39

ERROR in ./~/mime/types.json
Module parse failed: /Users/roman/src/private/parrot/node_modules/mime/types.json Line 1: Unexpected token :
You may need an appropriate loader to handle this file type.

What follows is a list of mime types...

rmnblm avatar Feb 25 '16 06:02 rmnblm

@rmnblm No, I did not. I think enlight's answer meant to create a browserWindow by the render process (another browserWindow instance), but I'm not sure since I did not try it. I later used ipcRenderer and ipcMain to communicate between the main thread and the renderer thread instead. Hope this may help :)

missingtrailingcomma avatar Feb 25 '16 07:02 missingtrailingcomma

@tinirlove Could you provide an example for your solution? :grin:

BTW: Do you use Electron with Webpack and React? You can read the full issue here: https://github.com/chentsulin/webpack-target-electron-renderer/issues/11

rmnblm avatar Feb 25 '16 07:02 rmnblm

@rmnblm TL;DR: full code here

sure! for this project, no, since I use Menu instead of browserWindow, but I need something like this.

code snippet for the main thread:

const electron = require('electron');
// ...
const ipcMain = electron.ipcMain;

function createInputBrowserWIndow(eventObj) {
  let addCountdownWindow = new BrowserWindow({
    // ...
  });

  const webContents = addCountdownWindow.webContents;

  webContents.on('did-finish-load', () => {
    // ...
    webContents.send('eventData', eventInfo);
  });
}

ipcMain.on('editOrCreate', function(ev, arg) {
  // ...
  ev.sender.send('updated', returnMsg);
});

code snippet for the renderer thread (browserWindow instance):

const ipcRenderer = require('electron').ipcRenderer;

ipcRenderer.on('eventData', function(event, msg) {
  // ...
});

function submitForm(e) {
  e.preventDefault();
  // ...
  ipcRenderer.send('editOrCreate', JSON.stringify(updatedData.concat([eventId])));

  ipcRenderer.on('updated', (ev, msg) => {
    alert(msg);
    window.close();
  });
}

missingtrailingcomma avatar Feb 25 '16 07:02 missingtrailingcomma

Accessing remote from index.html should works fine.

industral avatar Mar 29 '16 19:03 industral

I have had the same issue, but my project is basically following all the things here.

// main.js


// Modules to control application life and create native browser window
const {
    app,
    BrowserWindow
} = require('electron')
const path = require('path')

const createWindow = () => {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        frame: false,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true, // Enables Node.js integration in the renderer process
            contextIsolation: false, // Enables the Node.js integration to be able to load remote scripts
            enableRemoteModule: true,
            preload: path.join(__dirname, 'preload.js'),
        }
    })

    // and load the index.html of the app.
    mainWindow.loadFile('index.html')

    // Open the DevTools.
    // mainWindow.webContents.openDevTools()
    mainWindow.setAlwaysOnTop(true, "screen-saver")     // - 2 -
    mainWindow.setVisibleOnAllWorkspaces(true) 
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
    createWindow()

    app.on('activate', () => {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
// renderer.js
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const { remote } = require('electron');

const e = require('electron');

console.log(remote);
console.log(e)

const win = remote.getCurrentWindow(); /* Note this is different to the
html global `window` variable */



window.onbeforeunload = (event) => {
    /* If window is reloaded, remove win event listeners
    (DOM element listeners get auto garbage collected but not
    Electron win listeners as the win is not dereferenced unless closed) */
    win.removeAllListeners();
}

function handleWindowControls() {
    // Make minimise/maximise/restore/close buttons work when they are clicked
    document.getElementById('minimize-btn').addEventListener("click", event => {
        win.minimize();
        console.log('minimise');
    });

    document.getElementById('close-btn').addEventListener("click", event => {
        win.close();
        console.log("close");
    });

    console.log('window controls');
}
<!--index.html-->

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <!-- include the css -->
    <link rel="stylesheet" href="style.css">
    <title>Hello World!</title>
</head>

<body>

    <header id="titlebar">
        <div id="drag-region">




                <div id="closebutton">
                    <button id="close-btn">
                        <span class="close_circle"></span>
                    </button>
                </div>
                <div id="minimizebutton">
                    <button id="minimize-btn">
                        <span class="minimize_circle"></span>
                    </button>
                </div>
                <div id="fullscreenbutton">
                    <button id="fullscreen-btn-disabled">
                        <span class="fullscreen-circle"></span>
                    </button>
                </div>





        </div>
    </header>

    
    <script src="./renderer.js"></script>
</body>

</html>
// preload.js
// EMPTY

It has electron as an object, but remote doesnt exist. object console.log(require('electron')):

clipboard,
contextBridge,
crachReporter
ipcRenderer
nativeImage
shell
webFrame
deprecate

BlueFalconHD avatar May 14 '22 02:05 BlueFalconHD