文章目录
-
- iframe
- 输入网址
iframe
electron
窗口控件实际上是一个html
也就是说,通过分析工具,electron
可以用最短的代码写浏览器,甚至查看浏览器中的网页源代码,点击下图View
->Toggle Developer Tools
只需要一个代码main.js
const {
app, BrowserWindow} = require('electron') function createWindow () {
const mainWindow = new BrowserWindow({
width: 800,height: 600, }) mainWindow.loadURL('https://tinycool.blog.csdn.net/'); mainWindow.show() } app.whenReady().then(() => {
createWindow() app.on('activate', function () {
if (BrowserWindow.getAllWindows().length === 0) createWindow() }) })
其中,mainWindow.loadURL
用于加载链接。
当然,仅仅这样称之为浏览器是不够的,因为浏览器至少要自己输入链接。electron
中国提供了三种嵌入网页的方法,刚刚使用BrowserWindow只是第一个。
官方推荐的方法是iframe
,众所周知,这并不意外。iframe
是个html元素,专门用于网页内嵌。故而修改index.html
中的body
,将iframe
嵌入其中。
body> <div id="container" style="width:100%"> <input id="input" style="width:100%"> <iframe id="iframe" width="100%" src="https://tinycool.blog.csdn.net/" frameborder="0" onload="changeFrameHeight()"> </iframe> </div> </body>
其中,changeFrameHeight
为其加载时的事件,目的是让iframe
的尺寸和整个页面相适配,这个函数可定义在preload.js
中
function changeFrameHeight(){
var ifm= document.getElementById("iframe");
ifm.height=document.documentElement.clientHeight-50;
}
又考虑到当窗口尺寸发生变化时,也应该调用这个高度适配函数,故添加一个监听器
window.addEventListener('resize', function(){
changeFrameHeight();
})
输入网址
这回上面有个输入框了,可以输入网址,接下来实现这样的功能:输入网址后回车,则iframe
跳转到指定网址。这个功能十分简单,只需在加载的时候,为这个input
绑定一个回车事件
window.addEventListener('DOMContentLoaded', () => {
const input = document.getElementById("input");
const ifm = document.getElementById("iframe");
input.addEventListener("keydown", function(evt){
if(evt.key==="Enter"){
//当按下回车键时
updateURL(ifm,input.value)
}
})
})
function updateURL(ifm, url){
if (url.slice(0, 8).toLowerCase() != 'https://'
&& url.slice(0, 7).toLowerCase() != 'http://')
url = 'https://'+ url;
ifm.src = url //更新ifm的地址
}
效果为