小工具知识网

当前位置: 首页 > 行业知识 > 【Electron】webview 实现网页内嵌

行业知识

【Electron】webview 实现网页内嵌

2026-11-10 01:14:09 来源:互联网转载

实现效果:

当在输入框内输入某个网址后并点击button按钮 , 该网址内容就展示到下面

踩到的坑:之前通过web技术实现 iframe 标签内嵌会出现 同源策略,同时尝试过 vue.config.ts 内配置跨域项 那样确实 是实现啦 但不知道如何动态切换 tagert 的值 

同源策略:

Refused to frame 'https://www.baidu.com/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self' https://chat.baidu.com http://mirror-chat.baidu.com https://fj-chat.baidu.com https://hba-chat.baidu.com https://hbe-chat.baidu.com https://njjs-chat.baidu.com https://nj-chat.baidu.com https://hna-chat.baidu.com https://hnb-chat.baidu.com http://debug.baidu-int.com".

1. npm init -y //先安装package.json

2.npm install electron 

3.创建main.js

const { app, BrowserWindow } = require('electron')let mainWindowfunction createWindow () {  mainWindow = new BrowserWindow({    width: 1200,    height: 1000,    webPreferences: {      nodeIntegration: true,      webviewTag: true // 启用webview标签    }  })const menu = Menu.buildFromTemplate([]) // 设置菜单栏 =主进程Menu.setApplicationMenu(menu)  mainWindow.loadFile('index.html')  mainWindow.on('closed', () => {    mainWindow = null  })}app.whenReady().then(createWindow)app.on('window-all-closed', () => {  if (process.platform !== 'darwin') {    app.quit()  }})app.on('activate', () => {  if (BrowserWindow.getAllWindows().length === 0) {    createWindow()  }})

4.

Menu的作用是去除顶部菜单栏

const { Menu } = require('electron')const menu = Menu.buildFromTemplate([]) // 设置菜单栏 =主进程 Menu.setApplicationMenu(menu)

5.如果你在这里使用了 webview 标签 那么你一定要在 webPreferences内添加webviewTag并true ,因为在高版本的electron内 webview标签默认是禁用的状态 

                你好!                    Open URL                    urlInput = document.getElementById('urlInput')        openUrl = document.getElementById('openUrl')        foo = document.getElementById('foo')        openUrl.addEventListener('click', async () => {            foo.setAttribute('src', urlInput.value)        })    

启动命令:
npx electron . 

或

npm install -g electron
electron .

上一篇:华勤服务器怎么开机?

下一篇:揭秘Webgame源码,探索网页游戏开发的核心秘密!