In Electron, implement embedded web pages through webview and embed css styles and js scripts, etc.


Introduction of Electron, an open source library for building cross-platform desktop applications with HTML, CSS and JS, and building HelloWorld:


https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106413828


How Electron debugs the rendering process and uses the browser and VSCode to debug:


https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106414541


After setting up the project and knowing how to debug it


If you want to embed certain web pages, it is similar to the effect of an iframe.


Show webview


First add the webview tag in html





<div>  <webview id="wb" src="https://blog.csdn.net/BADAO_LIUMANG_QIZHI" /></div>

Set the address of the web page to be embedded directly through the src attribute.


Then open main.js and set the support webviewTag attribute to true

图片


Then run the project



 


preload attribute

The preload attribute can execute the specified script before all scripts in the webview are executed


In the webview tag in html


<webview id="wb" src="https://blog.csdn.net/BADAO_LIUMANG_QIZHI" preload="./js/preload.js"/>

Add the preload attribute and point to the specified script


In preload.js






setTimeout(()=>{    alert("粉丝数:"+document.querySelector('#fan').innerHTML);}, 5000);

Set to get the number of fans after five seconds, that is, get the content of the span by id


图片


 


Re-run the project


图片


Inject CSS and JS scripts


The webview instance can be obtained in js



const wb = document.querySelector('#wb');

然后通过设置其加载开始和加载完成的事件监听器对其进行css和js的注入


























//开始加载事件监听wb.addEventListener("did-start-loading", ()=> {    console.log("did-start-loading..."); })//停止加载事件监听wb.addEventListener("did-stop-loading", ()=> {    console.log("did-stop-loading...");     //注入css    wb.insertCSS(`    .title-blog {        background: red !important;    }    `)    //注入js脚本    wb.executeJavaScript(`        setTimeout(()=>{            alert("粉丝数:"+document.querySelector('#fan').innerHTML);        }, 2000);    `)    //打开调试工具    wb.openDevTools();})

运行项目看效果


 图片




Guess you like

Origin blog.51cto.com/15127572/2666803