目录
需求点:
1、打开任意网站,点击元素,获取元素xpath(这个在pc端就很难实现了,会涉及到跨域问题,所以用的electron)
2、获取的xpath需要回显到PC端网站,通过接口保存
思路:
1、electron实现获取xpath这一操作
2、pc端需要有 调起electron app 和 拿到 electron app 返回值的操作
3、传值
在传值上先后试过 mqtt、url+localstorage,mqtt因为延时,导致获取以后不能马上看到赋值,pass,url+localstorage就是electron app 通过打开一个新链接的方式跳转到pc,这样会每次打开一个新链接,并且涉及到要一直判断什么时候该保存,什么时候该清空,体验不太好,所以最后选择websocket
思路:
仅用于描述思路,代码不完整,不能直接使用
一、electron获取xpath
建2个窗口,主窗口通过 process.argv 获取 打开app时候的 参数,如果参数中包含url,则认为是pc端启动的app,这时候子窗口加载url地址,否则认为是单独启动app,这时候子窗口加载错误页面,提示需要pc端打开。
获取xpath用插件 (get-xpath)
1、创建主窗口
win = new BrowserWindow({
width: 1500,
height: 1200,
webPreferences: {
webSecurity: true,
webviewTag: true, // 开启webview
nodeIntegration: true, // 启用 Node.js 集成
preload: path.join(__dirname, "/static/js/preload.js"),
},
});
win.loadFile("./index.html");
2、创建子窗口并且setBrowserView到主窗口,子窗口默认加载error.html
view = new BrowserView({
webPreferences: {
webSecurity: true,
webviewTag: true, // 开启webview
nodeIntegration: true, // 启用 Node.js 集成
preload: path.join(__dirname, "./static/js/capturePage.js"),
},
});
view.setBounds({
x: 0,
y: 0,
width: 1500,
height: 1200,
horizontal: true,
vertical: true,
});
winWebContents = win.webContents;
viewWebContents = view.webContents;
win.setBrowserView(view);
viewWebContents.loadFile("./error.html");
3、如果获取到了url,就加载url
if (par && par.href && par.orderId && par.targetHref) {
viewWebContents.loadURL(par.href);
}
4、获取xpath并传递
上方代码有个(preload: path.join(__dirname, “./static/js/capturePage.js”) 在这里新建一个capturePage.js文件,文件里的功能需要实现:a.引入插件; b.拦截加载页面的原生点击事件;c.给点击事件加效果;d.传递获取到的xpath给主进程
const {
ipcRenderer } = require("electron");
const getXPath = require("get-xpath");
// 高亮的样式
const cla = "clickClass";
const style = "background:#ffeded;outline:2px dashed #ff5050;";
// box-sizing:border-box!important;
// 清空并初始化元素
function initDom(cla) {
const body = document.querySelector("html");
const allChoosedDom = body.querySelectorAll(`.