【前端小技能--electron】常用功能演示

1、设置右键菜单

监听右键事件,阻止默认事件

var rightTemplate = [
    {label:'复制',accelerator: "ctrl+c"},
    {label:'粘贴',accelerator: "ctrl+v",}
]
var m = remote.Menu.buildFromTemplate(rightTemplate)

// 添加右键事件
window.addEventListener('contextmenu', function(e){
    e.preventDefault();
    m.popup({
        window: remote.getCurrentWindow()
    })
})

2、通过链接打开外部浏览器

开发过程中,如果我们需要通过链接打开外部浏览器,则可以使用以下方法进行,shell模块

var {shell}  = require('electron')

var aHref = document.querySelector("#ahref")
aHref.onclick = function(e){
    e.preventDefault()
    var href = this.getAttribute("href")
    shell.openExternal(href)
}

3、BrowserView 嵌入网页

   var BrowserView = electron.BrowserView
    var view = new BrowserView()
    mainWindow.setBrowserView(view)
    view.setBounds({
        x:0,
        y:120,
        width:1000,
        height:680
    })
    view.webContents.loadURL("https://blog.csdn.net/qiuqiu1628480502/article/details/117998965")

4、子窗口中打开外链

使用window.open()

var mybtn = document.querySelector("#mybtn")
mybtn.onclick = function(e){
    window.open("https://www.baidu.com");
}

5、子窗口向父窗口传递信息

当我们想从子窗口向父窗口传递信息的时候,我们可以使用以下方法。

5.1 popup_page.html(子窗口)

window.opener.postMessage('我是子窗口传递的数据')

<body>
    <h2>我是弹出的子窗口</h2>
    <button id="popbtn">向父窗口传递信息</button>
</body>
<script>
    var popbtn = document.getElementById("popbtn");
    popbtn.onclick = function(){
        window.opener.postMessage('我是子窗口传递的数据')
    }
</script>
5.2 demo3.html
<button id="mybtn">打开子窗口</button>
<div id="mytext"></div>
<script src="./render/demo3.js"></script>
5.3 demo3.js(父窗口的js)

在父窗口中,我们可以使用window监听message事件,从msg中获取子窗口传递的信息。

window.addEventListener("message", (msg) => {
    var mytext = document.getElementById("mytext")
    console.log(msg);
    mytext.innerHTML = JSON.stringify(msg.data);
})

6、选择文件对话框

打开文件选择对话框可以使用dialog.showOpenDialog()方法来打开,它有两个参数,一个是设置基本属性,另一个是回调函数,如果是异步可以使用then来实现。

  • title : String (可选),对话框的标题
  • defaultPath : String (可选),默认打开的路径
  • buttonLabel : String (可选), 确认按钮的自定义标签,当为空时,将使用默认标签
  • filters : 文件选择过滤器,定义后可以对文件扩展名进行筛选
  • properties:打开文件的属性,比如打开文件还是打开文件夹,甚至是隐藏文件。
6.1 demo4.html
<body>
    <button id="mybtn">打开图片</button>
    <img id="dunpai" style="width:100%">
</body>
6.2 demo4.js
const { dialog } = require('electron').remote
    var openBtn = document.getElementById("mybtn");
    openBtn.onclick = function () {
        dialog.showOpenDialog({
            title: '请选择图片(我是自定义标题)',
            // 默认路径
            defaultPath: 'dunpai.png',
            // 只显示png结尾的文件及其他文件夹
            filters: [{ name: 'png', extensions: ['png'] }],
            // 设置弹框中的"打开"按钮
            buttonLabel: '打开盾牌'
        }).then(result => {
            console.log(result) // canceled filePaths
            let img = document.getElementById("dunpai")
            img.setAttribute("src", result.filePaths[0]);
        }).catch(err => {
            console.log(err)
        })
    }

buttonLabeltitledefaultPath:设置了这个值以后,文件框的按钮会变化,如下图所示:

在这里插入图片描述

7、保存文件对话框

使用node中的fs模块进行文件写入操作。

7.1 模块引入
const { dialog } = require('electron').remote
const fs = require('fs')
7.2 demo4.js
<button id="saveBtn">保存文件</button>

var saveBtn = document.getElementById("saveBtn");
    saveBtn.onclick = function(){
        dialog.showSaveDialog({
            title: '保存文件123'
        }).then(result => {
            fs.writeFileSync(result.filePath, '我是文件');
            console.log(result)
        }).catch( err => {
            console.log(err);
   })
}

8、消息对话框

消息对话框dialog.showMessageBox()

它有太多的属性,这里我们也只挑一些常用的属性来讲解,如果你在工作中具体使用,可以先到官网查询相关的API后,再根据需求具体使用。

  • type :String类型,可以选,图标样式,有noneinfoerrorquestionwarning
  • title: String类型,弹出框的标题
  • messsage : String 类型,必选 message box 的内容,这个是必须要写的
  • buttons: 数组类型,在案例中我会详细的讲解,返回的是一个索引数值(下标)
8.1 对话框
<button id="messageBtn">弹出对话框</button>
8.2 弹框
var messageBtn = document.getElementById("messageBtn")
    messageBtn.onclick = function(){
        dialog.showMessageBox({
            type: 'warning',
            title: '去么?',
            message: '周末去么?',
            buttons: ['我要去', '不去了']
        }).then(result => {
            console.log(result)
        })
    }
8.3 效果图

在这里插入图片描述

9、断网提醒功能

当网络中断或者网络恢复的时候,希望给用户一定的提示信息,

9.1 页面
<h2>断网提示</h2>
9.2 js代码
<script>
    window.addEventListener('online', function(){
        alert("网络恢复")
    })
    window.addEventListener('offline', function(){
        alert('网络中断,请稍后重试')
    })
</script>

10、底部消息通知

11、全局注册快捷键

ctrl+e,在窗口中打开“http://www.baidu.com”

使用globalShortcut

var globalShortcut = electron.globalShortcut

globalShortcut.register('ctrl+e', ()=>{
	mainWindow.loadURL('https://www.baidu.com');
})
注销快捷键

will-quit中进行快捷键的取消

app.on('will-quit', function(){
    //注销全局快捷键
    globalShortcut.unregister('ctrl+e')
    //全部注销
    globalShortcut.unregisterAll()
})

12、剪切板功能的使用

使用electron中的clipboard模块进行

12.1 页面
<p>激活码:<span id="code">12312321wqewqeq41231</span></p>
<button id="button">一键复制</button>
12.2 剪切板写入
const {clipboard} = require('electron')
const code = document.getElementById("code")
const button = document.getElementById("button")
button.onclick = function(){
	clipboard.writeText(code.innerHTML)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值