Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to use 'remote' module #3755

Closed
protozoo opened this issue Dec 10, 2015 · 18 comments
Closed

Unable to use 'remote' module #3755

protozoo opened this issue Dec 10, 2015 · 18 comments

Comments

@protozoo
Copy link

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 protozoo changed the title Unable ti use 'remote' module Unable to use 'remote' module Dec 10, 2015
@lee-dohm
Copy link
Contributor

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

@protozoo
Copy link
Author

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!

@lee-dohm
Copy link
Contributor

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

eac2e7c

Are you using v0.35.0 or above of Electron?

@herrmannplatz
Copy link
Contributor

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

@protozoo
Copy link
Author

@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
Copy link
Author

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

@miccferr
Copy link

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!

@renemonroy
Copy link

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

@miccferr
Copy link

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"  
  }

@renemonroy
Copy link

@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.

@missingtrailingcomma
Copy link

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!!

@enlight
Copy link
Contributor

enlight commented Feb 20, 2016

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

@rmnblm
Copy link

rmnblm commented Feb 25, 2016

@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...

@missingtrailingcomma
Copy link

@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 :)

@rmnblm
Copy link

rmnblm commented Feb 25, 2016

@tinirlove Could you provide an example for your solution? 😁

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

@missingtrailingcomma
Copy link

@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();
  });
}

@industral
Copy link

Accessing remote from index.html should works fine.

DanielFallon added a commit to DanielFallon/hain that referenced this issue Jan 11, 2017
per commit electron/electron@eac2e7c remote needs to be required as require('electron').remote

see discussion here:
electron/electron#3755

should alleviate concerns in this discussion:
hainproject#77
@BlueFalconHD
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests