Electron learning notes: the rendering process registers the callback pit with the main process

Time:2020-1-14

There will be an error in the following code

// main process
const el = require('electron');
el.app.testMain = {
    testName: 'main process object',
    testCallback: function(callback) {
        callback.apply(this);
    }
};


//Rendering process
const mt = require('electron').remote.app.testMain;
mt.testCallback(function() {
    console.log(this.testName);
});

The callback method of the render process is encapsulated as a name when it is called in the main process.callInRendererSo use theapplybindingthisIt is not actually bound to the callback method of the rendering process.

The following code can be solved:

// main process
const el = require('electron');
el.app.testMain = {
    testName: 'main process object',
    testCallback: function(callback) {
        callback.apply(null, [this]);
    }
};

//Rendering process
const mt = require('electron').remote.app.testMain;
mt.testCallback(function(ref) {
    console.log(ref.testName);
});