Sunday, 16 April 2017

Can't pass an IPC message to a browserwindow

I'm messing around with electron, one of the things i'm trying to do is monitor a directory for file changes, and send the full path of the file that changed to a browser window via IPC to a renderer. I know the file watcher is working since it's logging to the console, but the path never makes it to the browserwindow.

Putting logging lines in the renderer never log, and remote debugging and stepping through the code, i can see it never fires off to the renderer.

Any idea? I'm new to this javascript stuff so it's probably something simple i'm missing. Thanks in advance!

main.js:

const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain
const watchfiles = require('./watchfiles')
const windows = []

app.on('ready', _ => {
    [1].forEach(_ => {   
        let win = new BrowserWindow({
            height: 400,
            width: 400
    })

    win.loadURL(`file://${__dirname}/watchfiles.html`)


    win.on('closed', _ => {
    mainWindow = null
})
    windows.push(win)
})
})

ipc.on('filewatch-start', _ => {
    //Log
    console.log('Filewatch started')
    watchfiles(fullPath => {
        windows.forEach(win => {
            win.webContents.send('changedfiles', fullPath)
        })
    })
})

renderer.js:

const electron = require('electron')

const ipc = electron.ipcRenderer

document.getElementById('start').addEventListener('click', _ =>{
    ipc.send('filewatch-start')
})

ipc.on('changedfiles', (event, message) => {
document.getElementById('changedfiles').innerHTML = message
}) 

watchfiles.js:

module.exports = function watchfiles(watchr) {

    // Import the watching library
var watchr = require('watchr')

// Define our watching parameters
var path = process.cwd()
function listener (changeType, fullPath, currentStat, previousStat) {
    switch ( changeType ) {
        case 'update':
            console.log('the file', fullPath, 'was updated', currentStat, previousStat)
            break
        case 'create':
            console.log('the file', fullPath, 'was created', currentStat)
            break
    }
}
function next (err) {
    if ( err )  return console.log('watch failed on', path, 'with error', err)
    console.log('watch successful on', path)
}

// Watch the path with the change listener and completion callback
var stalker = watchr.open(path, listener, next)

// Close the stalker of the watcher
//stalker.close()
}

watchfile.html:

<html>
    <head>
        <link rel="stylesheet" href="watchfiles.css" />
    </head>
    <body>
        <div id="container">
        <h1 class="title">Watching files:</h1>
        <div class="watchfiles" id="changedfiles"></div>
        <button class="btn" id="start">Start</button>
        </div>
        <script>require('./renderer')</script>
    </body>
</html>



via Dan C.

No comments:

Post a Comment