#how to use preload correctly

8 messages · Page 1 of 1 (latest)

lyric jay
#

I'm trying to load a library in preload.js

const { contextBridge } = require("electron");
const mineflayer = require("mineflayer");

contextBridge.exposeInMainWorld('libs', {
    mine: mineflayer
});

In main.js I connect preload in this way

    win = new BrowserWindow({
        resizable: false,
        width: 900,
        height: 700,
        autoHideMenuBar: true,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true,
            sandbox: false
        }
    });

I want to use this library in index.js (js script of the index.html file)
The first method works but the next one does not work

lib.method() - works

lib.method(options).method() is not a function

const bot = libs.mine.createBot({option});

bot.on("message", msg => {console.log(msg)}); // bot.on it is not a function

I can’t solve this problem for 2 days, what’s the problem?

stray trout
#

don't pass the whole mineflayer thought IPC

#

only expose what you need

#
contextBridge.exposeInMainWorld('libs', {
  on: (channel) => {
    const bot = mineflayer.createBot({ option });
    bot.on(channel, msg => { console.log(msg) });
  }
});
window.libs.on("message")
lyric jay
stray trout
#

this was an example

#

adapt the code to your needs

lyric jay
#

I understand that this is just an example, but I don't understand at all how to properly adapt the code.