在渲染过程中未定义的上下文桥中的 API

开发

我一直致力于将电子应用程序从 11.x 更新到 12.x,但遇到了一个问题,即contextBridge.exposeInMainWorld当通过窗口调用时,由 声明的 api未定义。

这是我的 preload.js 文件

const { contextBridge, ipcRenderer } = require('electron');
const { path } = require('path')

contextBridge.exposeInMainWorld('api',{
    getPath: (filePath) => {
        return path.parse(filePath).base;
    },

    removeAllListeners: (ListenerType) => {
        ipcRenderer.removeAllListeners(ListenerType);
    },

    openNewPDF: (pdf) => {
        ipcRenderer.send('openNewPDF',pdf);
    },
    newWindow: (file) => {
        ipcRenderer.send('newWindow',file);
    },
    togglePrinting: (value) => {
        ipcRenderer.send('togglePrinting',value)
    },
    resizeWindow: (value) => {
        ipcRenderer.send('resizeWindow', value)
    }
});

我的 app.js

function createWindow(filename = null) {
    // Create the browser window.
    let win = new BrowserWindow({
        width: 550,
        height: 420,
        minWidth: 565,
        minHeight: 200,
        preload: path.resolve(path.join(__dirname, 'app/preload.js')),
        resizable: true,
        titleBarStyle: 'default',
        show: false
    });
    wins.push(win);

    // and load the index.html of the app.

    win.loadFile('app/index.html');
    win.openDevTools();
    let wc = win.webContents
    wc.on('will-navigate', function (e, url) {
        if (url != wc.getURL()) {
            e.preventDefault()
            shell.openExternal(url)
        }
    })

    win.once('closed', () => {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        wins = [];
    });

    win.webContents.removeAllListeners('did-finish-load');
    win.webContents.once('did-finish-load', () => {
        if (filename) {
            win.webContents.send('file-open', filename);
            win.show();
        } else {
            win.show();
        }
    });


    if (!menuIsConfigured) {
        const menu = Menu.buildFromTemplate(menuTemplate);

        menu.getMenuItemById('file-open').click = () => {
            openNewPDF();
        };

        menu.getMenuItemById('file-print').click = () => {
            const focusedWin = BrowserWindow.getFocusedWindow();
            focusedWin.webContents.send('file-print');
        };

        Menu.setApplicationMenu(menu);
        menuIsConfigured = true;
    }

    const openNewPDF = () => {
        dialog
            .showOpenDialog(null, {
                properties: ['openFile'],
                filters: [{ name: 'PDF Files', extensions: ['pdf'] }]
            })
            .then((dialogReturn) => {
                const filename = dialogReturn['filePaths'][0];
                if (filename) {
                    if (wins.length === 0) {
                        createWindow(filename.toString());
                    } else {
                        const focusedWin = BrowserWindow.getFocusedWindow();
                        if (focusedWin) {
                            focusedWin.webContents.send('file-open', filename.toString());
                        }
                    }
                }
            });
    }

    ipcMain.removeAllListeners('togglePrinting');
    ipcMain.once('togglePrinting', (e, msg) => {
        const menu = Menu.getApplicationMenu();
        menu.getMenuItemById('file-print').enabled = Boolean(msg);
    });

    ipcMain.removeAllListeners('newWindow');
    ipcMain.once('newWindow', (e, msg) => {
        console.log('opening ', msg, ' in new window');
        createWindow(msg);
    });

    ipcMain.removeAllListeners('resizeWindow');
    ipcMain.once('resizeWindow', (e, msg) => {
        const { width, height } = win.getBounds();
        if (width < 1000 || height < 650) {
            win.setResizable(true);
            win.setSize(1000, 650);
            win.center();
        }
    });

    ipcMain.removeAllListeners('openNewPDF');
    ipcMain.once('openNewPDF', (e, msg) => {
        openNewPDF();
    });
}

let fileToOpen = '';

const args = process.argv;
const argsLength = args.length;
if (argsLength > 1 && args[argsLength - 1].endsWith('.pdf')) {
    fileToOpen = args[argsLength - 1];
}

app.on('open-file', (event, path) => {
    event.preventDefault();
    if (app.isReady()) {
        if (wins.length === 0) {
            createWindow(path.toString());
        } else {
            const focusedWin = BrowserWindow.getFocusedWindow();
            focusedWin.webContents.send('file-open', path.toString());
        }
    }
    fileToOpen = path.toString();
});

app.whenReady().then(() => {
    if (fileToOpen) {
        createWindow(fileToOpen);
    } else {
        createWindow();
    }
});


app.on('window-all-closed', () => {
    app.quit()
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

contextBridge不知道为什么不起作用。

阿布希耶莱

传递给BrowserWindow构造函数的对象不正确。preload选项应该是一个属性webPreferences

const win = new BrowserWindow({
  webPreferences: {
    preload: YOUR_PRELOAD_SCRIPT_PATH
  }
});

查看文档

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用上下文 API 在函数组件中未定义反应状态属性

上下文API问题-对象未定义

设置状态时React上下文api返回未定义

无法从Promise,上下文API(反应钩子)读取未定义的属性“代码”

在服务器端渲染中未定义的React上下文

构造函数中未定义上下文 - 反应

功能中未定义的名称“上下文”

React 中未定义上下文值

颤振中的上下文问题“未定义的名称'上下文'”

Facebook api调用中/ me的上下文是什么?

api.ai 中的上下文数组

跨边界上下文的DDD中的API与事件

对象没有被推入上下文 api 中的数组

如何从上下文 API 中的组件调用函数?

在next.js中使用带有useReducer钩子的上下文Api可以在调用useContext时返回未定义的

反应中未定义的 API 数据

渲染问题API级别24中的渲染过程中引发异常

如何从 AWS API Gateway 自定义授权方检索 Spring Boot 中的上下文对象?

在 UI 中添加和删除项目时,React Context API 上下文 API 问题

在片段中嵌套的AdapterView.OnItemClickListener(){}中传递活动的上下文-方法未定义

反应上下文-“ this”未定义

ReferenceError:上下文未定义

上下文未定义

反应上下文未定义

上下文返回未定义

从渲染过程中要求电子对话框未定义

从React上下文API中的列表中删除记录后,无法设置道具值

从存储过程中调用API

JS:“这个”上下文在promise链中时始终显示为未定义