8、electron嵌入网页

1、新建渲染进程 “嵌入网页.htm”

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="button" id="btn" value="打开嵌入网页的新窗口" />

    <script>
        const remote = require('@electron/remote');
        const BrowserWindow = remote.BrowserWindow;
        const BrowserView = remote.BrowserView;

        const btn = document.querySelector("#btn");
        
        window.onload = function(){
            btn.onclick=()=>{
                newWin = new BrowserWindow({
                    width:500,
                    height:500
                });
                newWin.loadFile("子窗口.html");
                newWin.on("closed",()=>{
                    newWin = null;
                });

                //嵌入网页
                let view = new BrowserView();
                newWin.setBrowserView(view);
                view.setBounds({x:0,y:120,width:1000,height:680});
                view.webContents.loadURL('https://www.cnblogs.com/handsomeziff/');
            }
        }
        
    </script>
</body>
</html>

2、子窗口.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>我是子窗口</h1>

    <script>
        
    </script>
</body>
</html>
View Code

3、主进程序index.js代码:

 1 var electron = require('electron')
 2 
 3 var app = electron.app   //引用APP
 4 var BrowserWindow = electron.BrowserWindow;  //窗口引用
 5 var mainWindow = null;  //声明要打开的主窗口
 6 
 7 app.on('ready',()=>{
 8     mainWindow = new BrowserWindow({
 9         width:800,
10         height:800,
11         webPreferences:
12         {
13             nodeIntegration:true,
14             contextIsolation:false,
15             enableRemoteModule: true,  //允许使用remote模块
16         }
17     });
18 
19     require("@electron/remote/main").initialize();  //初始化remote模块
20     require("@electron/remote/main").enable(mainWindow.webContents);  //
21 
22     require('./menu.js')
23     //mainWindow.loadFile('index.html');
24     //mainWindow.loadFile('打开新窗口.html');
25     //mainWindow.loadFile('通过浏览器打开链接.html');
26     mainWindow.loadFile('嵌入网页.htm');
27     
28     mainWindow.openDevTools();
29     mainWindow.on('close',()=>{
30         mainWindow = null;   //关闭窗口释放资源
31     })
32 });
View Code

 

posted @ 2022-12-09 15:55  ziff123  阅读(727)  评论(0编辑  收藏  举报