小墨の博客

梦想需要付诸行动,否则只能是梦

Electron 点击全屏

通过发送消息的方式进行传递,这样即使是内部嵌入的跨域 iframe 页面也可以发送消息到父页面实现。

首先,在页面中绑定元素点击事件。

// 点击全屏
document.getElementById("fullscreen-button").addEventListener("click", function () {
    if (document.fullscreenElement) {
        document.exitFullscreen();
    } else {
        if(inElectron) {
            // electron 中
            const message = JSON.stringify({
                action: 'fullscreen'
            });
            window.parent.postMessage(message, '*');
        } else {
            // 浏览器中
            document.body.requestFullscreen()
        }
    }
})


在electron的 preload.js 中接收 message 消息

const { ipcRenderer } = require('electron')

window.addEventListener('message', function (e) {
    // 获取消息内容 data
    const { data } = e;
    console.log("[electron preload]", data)
    try {
        let message = JSON.parse(data);
        console.log(message)
        switch (message.action) {
            case 'fullscreen':
                ipcRenderer.send('toggle-fullscreen')
                break
        }
    } catch (err) {
        console.log("err", err)
    }
})


修改 electron 的 main.js 

// 👇👇👇记得引入 ipcMain
const { app, BrowserWindow, ipcMain, Menu, globalShortcut } = require('electron')
const { platform } = require('node:process')
const path = require('path')

console.log(`This platform is ${platform}`);

const createWindow = () => {
    // 创建窗口
    const mainWindow = new BrowserWindow({
        width: 1080,
        minWidth: 760,
        height: 720,
        minHeight: 480,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        },
    })

    // 加载 HTML
    mainWindow.loadFile('html/index.html')

    // 隐藏菜单栏
    // let menu = Menu.getApplicationMenu()
    Menu.setApplicationMenu(null)

    // 👇👇👇核心代码
    // 全屏逻辑
    // mainWindow.fullScreen = true;
    ipcMain.on('toggle-fullscreen', () => {
        mainWindow.setFullScreen(!mainWindow.isFullScreen())
    })

    // 配置ESC键退出全屏
    globalShortcut.register('ESC', () => {
        mainWindow.setFullScreen(false);
    })

    // 调试窗口
    // mainWindow.webContents.openDevTools()
}

app.whenReady().then(() => {
    createWindow()

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

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})



本文由张小弟之家原创。

张小弟之家

本文链接:
文章标题:

本站文章除注明转载/出处外,均为原创,若要转载请务必注明出处。转载后请将转载链接通过邮件告知我站,谢谢合作。本站邮箱:admin@only4.work

尊重他人劳动成果,共创和谐网络环境。点击版权声明查看本站相关条款。

    发表评论:

    搜索
    本文二维码
    标签列表
    站点信息
    • 文章总数:507
    • 页面总数:20
    • 分类总数:92
    • 标签总数:207
    • 评论总数:60
    • 浏览总数:219202

    | | |
    | |  Z-Blog PHP