文章目录
- iframe
- 输入网址
源码地址: electron做一个丐版浏览器,只有输入网址显示网页的功能,适合学习
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/');
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/"
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的地址
}
效果为
更多推荐
用electron做一个浏览器
发布评论