electron_issues
停止和退出
app.quit未完全结束进程
在exe执行中未现问题
Cannot find module ‘./src/….’
Github Issue
将文件pattern添加到electron-builder的打包规则中
另外,require import的路径均不区分大小写,configure.ts被活生生编译并打包为Configure.js以及Configure.map.js
import编译成require,找不到configure
无边透明窗体显示时出现闪烁 Issue#10069
该问题是由于webview plugin无法设置透明背景造成的,在BrowserWindow show过程中显示了webview的白色背景,目前的workaround可以延迟页面内容的显示1
2
3
4
5
6
7function showBrowserWindow() {
win.setOpacity(0);
win.show();
setTimeout(() => {
win.setOpacity(1);
}, 50);
}
rebuild fail
1
2 gyp ERR! clean error
gyp ERR! stack Error: EPERM: operation not permitted, unlink 'D:\projxxx\node_modules\ref\build\Release\binding.node'
往往是项目文件正在使用中(正在参与其他进程的编译或执行)
oauth2
早先本机应用程序使用嵌入的用户代理(嵌入的web view)进行OAuth授权请求,这种方法有很多缺点,包括主机应用程序
能够复制用户凭据和Cookie,以及需要在每个应用程序中从头进行身份验证的用户。IETF RFC 8252。
使用浏览器被认为更加安全且容易保留认证状态2026-07 修订:这条仍然成立。本机应用包括 Electron,应优先使用系统浏览器 + Authorization Code + PKCE,而不是在
BrowserWindow/webview中嵌入登录页。旧示例中的response_type=id_token token属于 implicit/hybrid 风格,今天不建议作为新实现。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+
| User Device |
| |
| +--------------------------+ | (5) Authorization +---------------+
| | | | Code | |
| | Client App |---------------------->| Token |
| | |<----------------------| Endpoint |
| +--------------------------+ | (6) Access Token, | |
| | ^ | Refresh Token +---------------+
| | | |
| | | |
| | (1) | (4) |
| | Authorizat- | Authoriza- |
| | ion Request | tion Code |
| | | |
| | | |
| v | |
| +---------------------------+ | (2) Authorization +---------------+
| | | | Request | |
| | Browser |--------------------->| Authorization |
| | |<---------------------| Endpoint |
| +---------------------------+ | (3) Authorization | |
| | Code +---------------+
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+
对于 electron,渲染界面提供入口 signin,点击后调用默认浏览器打开登录页,authenticate 通过后,重定向过程会将授权码返回到 electron。这个“返回”过程可以使用自定义协议实现,也可以使用 loopback localhost callback。
重定向过程会将授权码或直接将access token返回到electron
2026-07 修订:新实现应让浏览器只返回 authorization code,Electron 客户端再用 PKCE 的
code_verifier换 token。不要让 access token 出现在 URL fragment 中,也不要在 renderer 中长期保存 token。
推荐流程:
- Electron 主进程生成
code_verifier、code_challenge、state、nonce。 - 使用
shell.openExternal(authUrl)打开系统浏览器。 - 通过自定义协议或 localhost callback 收到
code和state。 - 校验
state,用code_verifier请求 token。 - token 存储放在系统凭据管理器、加密存储或主进程内存中,renderer 只拿业务所需的最小状态。
renderUI1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24signinWithADB2C(){
const adconfig={
clientid:'3c744214-bf78-4f92-8173-49863ae8f24b',
authority:'https://qqstudio.b2clogin.com/qqstudio.onmicrosoft.com/B2C_1_basic_sign_up_and_sign_in',
redirectUri:'http://localhost:9990/index.html',
scopes:'3c744214-bf78-4f92-8173-49863ae8f24b openid'
}
// make up / assemble authority URL
const authorityURL = `${adconfig.authority}/oauth2/v2.0/authorize?client_id=${
adconfig.clientid
}&redirect_uri=${
encodeURI(adconfig.redirectUri)
}&scope=${
encodeURI(adconfig.scopes)
}&response_type=id_token%20token&nonce=defaultNonce&prompt=login`;
// call main process open URL with default browser
// meanwhile launch a http server
this.ipcService.send('openinbroweser', authorityURL);
this.loading = true;
// listen Logged in message
this.ipcService.on('access_token', msg => {
// TODO process user info
});
}
2026-07 修订:上面代码仅作历史记录。新代码应改为
response_type=code,并添加code_challenge、code_challenge_method=S256、随机state和nonce。
main 主线程中launch一个http server,负责提供Redirect URI的页面,页面自执行request请求,请求亦由http server响应1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29....
ipcMain.on('openinbroweser', (event, args) => {
log('info', 'ipcmain event:openinbroweser');
if (args) {
const { shell } = require('electron');
shell.openExternal(args);
} else {
log('error', 'invalid website', args);
}
});
// launch a http server
var static = require('node-static');
var file = new static.Server(`${__dirname}/public`);
http.createServer(function (request, response) {
if(request.url==='/index.html'){
request.addListener('end', function () {
file.serve(request, response)
}).resume();
}else{
const reg = new RegExp("t=([^&]*)");
const res= request.url.match(reg);
const token = res[1];
console.log('t=',token)
win.webContents.send('access_token',token)
response.write("success"); //close default browser
}
response.end(); //end the response
}).listen(9990)
redirect page (public/index.html)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20<html>
<body>
<p>serve by csportal</p>
<script>
(() => {
var reg = new RegExp("#access_token=([^&]*)");
var res = location.href.match(reg);
var token = unescape(res[1]);
fetch(`http://localhost:3000?t=${token}`)
.then(function (response) {
return response.json();
})
.catch(error => console.error('Error:', error))
.then(response => {console.log('Success:', response);
window.close();
});
})();
</script>
</body>
</html>
Caution! 需考虑到浏览器将token传递给client的过程,都有被第三方恶意应用占用URL Scheme或者localhost端口截取Access Token的风险。在有”显式”授权流程的方式中,浏览器传递授权码,由client凭授权码换取token,同样无法杜绝第三方拦截。
了解使用带有PKCE(Proof Key for Code Exchange)支持的授权码模式
2026-07 新增:Electron OAuth 安全清单
state必须随机且单次使用,callback 必须校验。- localhost callback 使用随机端口,并尽量只监听
127.0.0.1。- 自定义协议要考虑被其他应用抢注的风险。
- 不在 renderer、localStorage、日志、URL 中暴露 token。
- 打开外部链接前校验协议和 host,避免被恶意 URL 利用。
NSIS宏
NSIS(Nullsoft Scriptable Install System)
Macros are used to insert code at compile time, depending on defines and using the values of the defines. The macro’s commands are inserted at compile time. This allows you to write general code only once and use it a lot of times but with few changes
如上所述,宏的作用是“insert”代码,和通常的编程语言中的#define是一样的。insert的锚点标识是!insertmacro
宏指令
1 | !macro Hello |
含参宏
1 | !macro Hello What |
node-ffi
node-ffi (Node.js Foreign Function Interface)
install:1
npm i ffi
如果install的ffi有问题,可以拉source下来编译
compile:1
2
3
4npm i -g node-gyp
git clone git://github.com/node-ffi/node-ffi.git
cd node-ffi
node-gyp rebuild
Node FFI Tutorial
node-ffi 停止更新当前不支持最新版本node.js,事实上 经QQs实践基于node10的electron6无法与之集成构建,Github上有替代方案 node-ffi-napi
websocket
ws: a Node.js WebSocket library
ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and
server implementation.
Passes the quite extensive Autobahn test suite: server,
client.
Note: This module does not work in the browser. The client in the docs is a
reference to a back end with the role of a client in the WebSocket
communication. Browser clients must use the nativeWebSocket
object(QQs: browser client should call the Websocket constructor provided by browser, see the example at bottom of this article). To make the same code work seamlessly on Node.js and the browser, you
can use one of the many wrappers available on npm, like
isomorphic-ws.
Table of Contents
- ws: a Node.js WebSocket library
Protocol support
- HyBi drafts 07-12 (Use the option
protocolVersion: 8) - HyBi drafts 13-17 (Current default, alternatively option
protocolVersion: 13)
Installing
1 | npm install ws |
Opt-in for performance and spec compliance
There are 2 optional modules that can be installed along side with the ws
module. These modules are binary addons which improve certain operations.
Prebuilt binaries are available for the most popular platforms so you don’t
necessarily need to have a C++ compiler installed on your machine.
npm install --save-optional bufferutil: Allows to efficiently perform
operations such as masking and unmasking the data payload of the WebSocket
frames.npm install --save-optional utf-8-validate: Allows to efficiently check if a
message contains valid UTF-8 as required by the spec.
API docs
See /doc/ws.md for Node.js-like documentation of ws classes and
utility functions.
WebSocket compression
ws supports the permessage-deflate extension which enables
the client and server to negotiate a compression algorithm and its parameters,
and then selectively apply it to the data payloads of each WebSocket message.
The extension is disabled by default on the server and enabled by default on the
client. It adds a significant overhead in terms of performance and memory
consumption so we suggest to enable it only if it is really needed.
Note that Node.js has a variety of issues with high-performance compression,
where increased concurrency, especially on Linux, can lead to catastrophic
memory fragmentation and slow performance. If you intend to use
permessage-deflate in production, it is worthwhile to set up a test
representative of your workload and ensure Node.js/zlib will handle it with
acceptable performance and memory usage.
Tuning of permessage-deflate can be done via the options defined below. You can
also use zlibDeflateOptions and zlibInflateOptions, which is passed directly
into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs].
See [the docs][ws-server-options] for more options.
1 | const WebSocket = require('ws'); |
The client will only use the extension if it is supported and enabled on the
server. To always disable the extension on the client set theperMessageDeflate option to false.
1 | const WebSocket = require('ws'); |
Usage examples
Sending and receiving text data
1 | const WebSocket = require('ws'); |
Sending binary data
1 | const WebSocket = require('ws'); |
Simple server
1 | const WebSocket = require('ws'); |
External HTTP/S server
1 | const fs = require('fs'); |
Multiple servers sharing a single HTTP/S server
1 | const http = require('http'); |
Client authentication
1 | const http = require('http'); |
Also see the provided example using express-session.
Server broadcast
A client WebSocket broadcasting to all connected WebSocket clients, including
itself.
1 | const WebSocket = require('ws'); |
A client WebSocket broadcasting to every other connected WebSocket clients,
excluding itself.
1 | const WebSocket = require('ws'); |
echo.websocket.org demo
1 | const WebSocket = require('ws'); |
Use the Node.js streams API
1 | const WebSocket = require('ws'); |
Other examples
For a full example with a browser client communicating with a ws server, see the
examples folder.
Otherwise, see the test cases.
FAQ
How to get the IP address of the client?
The remote IP address can be obtained from the raw socket.
1 | const WebSocket = require('ws'); |
When the server runs behind a proxy like NGINX, the de-facto standard is to use
the X-Forwarded-For header.
1 | wss.on('connection', function connection(ws, req) { |
How to detect and close broken connections?
Sometimes the link between the server and the client can be interrupted in a way
that keeps both the server and the client unaware of the broken state of the
connection (e.g. when pulling the cord).
In these cases ping messages can be used as a means to verify that the remote
endpoint is still responsive.
1 | const WebSocket = require('ws'); |
Pong messages are automatically sent in response to ping messages as required by
the spec.
Just like the server example above your clients might as well lose connection
without knowing it. You might want to add a ping listener on your clients to
prevent that. A simple implementation would be:
1 | const WebSocket = require('ws'); |
How to connect via a proxy?
Use a custom http.Agent implementation like https-proxy-agent or
socks-proxy-agent.
Changelog
We’re using the GitHub releases for changelog entries.
License
[node-zlib-deflaterawdocs]:
https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options
[ws-server-options]:
https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback
Browser Client
1 | // Create WebSocket connection. |
GitFlow
Branch
- master
- dev
- feature/xxxx
- release/1.x.x
hotfix/1.x.x
Tag
hotfix 合并到master 以及 dev
1
2git checkout master
git merge --no-ff hotfix/1.x.x关于QA的讨论
曾认为feature代码在开发确认功能,过静态检查、单元测试、code review后合并至dev,即feature所在的生命周期由开发团队维护,从dev做release交QA进行全量测试
实际上在本团队,feature的DOD(defination of done)规定在合并到dev前需要通过QA测试,对合并后再发的’版本’也肯定要测的。
对于本团队的实践,是否存在QA过早介入,测试是否重复的问题,fcc大佬如是说:多数情况下new feature的业务/逻辑上的确认只能人工进行,这里的人是QA的人是合理的,该‘确认’过程不包含在code review(主要针对编码质量)中,若无QA的确认,则存在合并后被QA拒绝的风险,而拆解合并后的代码可能代价颇高。
另:了解gitlabmaster 只合并
- dev 拉feature 完成合并到dev
- dev 拉release 测试后合并到 master 和 dev
为什么不直接测dev?拉release相当于锁定dev状态 此时dev可以接收合并 防止dev遭合并破坏时影响release进程 同时支持多release版本并行
- release 有bug 在当前分支修改后 需合并到 dev
- 线上紧急修复 master分支拉hotfix 修复后合并到master dev
jenkins参数化
使用Git Parameter简化GitFlow工作方式的持续集成
- 安装Git Parameter Plugin
- 设置 Jenkins Job ‘this project is parameterized’
- 设置变量BRANCH_NAME,变量类型为Branch or Tag, 默认为master
- 设置 Source Code Management - Branches to build 为 $BRANCH_NAME
完成后可使用该项目的build with Parameters功能,即选择特定分支进行构建
CAS
Git
日常
1 | git config --global user.email "QQs@xxxx.xxx" |
clone指定分支
1 | git clone -b release git@xxxx.xxx:projectX.git |
创建分支
1 | git checkout -b bug/fixXXXissue |
忽略本地修改拉取远程分支
1 | git fetch --all |
可以认为git pull是git fetch和git merge两个步骤的结合
git pull <远程主机名> <远程分支名>:<本地分支名>
//取回远程主机某个分支的更新,再与本地的指定分支合并。
1 | git fetch origin master:temp |
回退1
git reset --hard cd8462xxxx
即将HEAD游标指向到之前的一次commit
git clean -fxd
-f —force
-x 移除包括被gitignore忽略的文件 支持-e参数(if have)
-X 移除所有git ignore的文件 用于从头开始重建一切
-d 递归并移除untrack目录
部分检出
1 | git config core.sparsecheckout true |
reset revert
1 | git reset --soft <commit> // 重置到<commit>版本,修改内容放入缓存区(unstage) |
rebase
1 | git checkout feature/new_featueXXX |
1 | git rebase -i <start-commit> <end-commit> //(start-commit, end-commit] 前开后闭区间,合并到当前分支,默认 end-commit 为当前 HEAD |
把 develop rebase 进 feature/new_featueXXX 分支,develop为上游(Upstream), checkout 的new_featueXXX 分支为Currnet Branch.
每将一次develop的commit rebase进feature 都合并为一个中间版本commit,然后 git rebase —continue。实际中,rebase过程中可能产生冲突,如果两条分支都含有多次commit,且修改内容相互渗透,产生很多冲突,continue时是个中间版本 很难保证复合变基的逻辑吧 那将使这种”规范”失去意义 索性直接merge算了
rebase的取消
rebase完成后没有与该操作对应的commit记录,即不改变前后commit的个数(只调整顺序)但是git本身是有所有操作的记录的,因此任何操作都可以回退, 使用git reflog显示这些记录 并选择标记头进行回退1
2
3git reflog
---显示action历史---
git reset --hard HEAD{10}
git rebase 的撤销
包括git reset到之前的版本,此时HEAD会指向到旧版本,较新的commit不在git log中可见了,可以通过git reflog查看 tip: git reflog —date=iso查看操作时间
找到commit的SHA号码 git reset到它即可
git cherry-pick
1 | git checkout develop |
例如f2ef69d 9839b06是release上刚修好的bug,可以使用上述命令将两处修改直接复制到develop分支
repository 迁移
1 | git clone --bare git@old-repo.git |
stale branches 和 remote tracking branch
remote tracking branch是一个引用(reference),表示是远端分支的状态,不应被修改
stale branch是远端已经移除的remote tracking branchStackOverflow:What is a “stale” git branch?
git log
退出日志文本是按q,同vim
查看所有分支对当前目录的修改,并显示所修改文件:
git log —stat —graph —all
stage
git status
git add/rm
git reset ./temp.txt
git checkout —
tag
标签tag用于标记一个commit1
git tag -a v1.0.3 -m "bump version to v1.0.3"
使用git tag命令查看所有标签,使用git checkout检出指定标签版本
移除尚未推送到远端的标签:1
git tag -d v1.0.3
git blame
submodule
为项目添加子模块1
git submodule add https://example.com/demo/lib1 lib1
关联了子模块的项目含有.gitmoudles文件 形如1
2
3
4
5
6
7
8
9[submodule "lib1"]
path = lib1
url = https://example.com/demo/lib1
[submodule "lib2"]
path = lib2
url = https://example.com/demo/lib2
[submodule "lib3"]
path = lib3
url = https://example.com/demo/lib3
拉取项目后源码中不包含这些子项目 使用git submodule命令更新1
2
3git submodule init lib1 lib2 #init命令可以按需初始化 lib1 lib2写入项目config
git submodule update
大型项目递归拉取submodule1
git submodule update --init --recursive
ssh协议改https
1 | git remote add temp_remote_name https://xxxxxxx.git |
git worktree
1 | git worktree add -b feature-render ..\project-feature-render |
git worktree 区别于 git clone 共享git对象数据库 比git clone要快
worktree目录中看不到完整的git log 仿佛是新的仓库 不能checkout其他分支 但是可以rebase
使用pnpm避免node_modules重复
git flow
feat 增加新的业务功能
fix 修复业务问题 / BUG
perf 优化性能
style 更改代码风格,不影响运行结果
refactor 重构代码
revert 撤销更改
test 测试相关,不涉及业务代码的更改
docs 文档和注释相关
chore 更新依赖 / 修改脚手架配置等琐事
workflow 工作流改进
ci 持续集成相关
types 类型定义文件更改
troubleshooting
error: object file .git/objects/61/9151e2619bc36c3c4f5f0c86432b2ca651706d is empty fatal: loose object 619151e2619bc36c3c4f5f0c86432b2ca651706d (stored in .git/objects/61/9151e2619bc36c3c4f5f0c86432b2ca651706d) is corrupt
尝试用下列方法修复1
2
3# 删除.git/objects/*/目录下的空文件
git fsck --full
git gc --auto
git fsck命令用于检查文件有效性和连贯性
git gc 清理不必要的文件并优化本地存储库
form-data 以及 basic auth
Postman

Node.js Server1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19const express = require('express');
const app = express();
var multer = require('multer');
var upload = multer();
// Parse URL-encoded bodies (as sent by HTML forms)
app.use(express.urlencoded());
// for parsing multipart/form-data
app.use(upload.array());
app.use(express.static('public'));
app.post('/', function(request, response){
console.log(request.body);
response.json({res:'ok',data:request.body})
});
const listener = app.listen(process.env.PORT || 3000, function () {
console.log('Your app is listening on port ' + listener.address().port);
});
Node.js client1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31const http = require('http')
const FormData = require('form-data')
function btoa(str) {
return Buffer.from(str).toString('base64')
}
const formData = new FormData();
formData.append('username', 'QQs');
formData.append('password', btoa('*****'));
const authorizationData = 'Basic ' + btoa('authorizationID:authorizationPassword');
const options = {
hostname: 'localhost',
port: 3000,
path: '',
method: 'POST',
headers: formData.getHeaders(),
auth: authorizationData
};
const req = http.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
formData.pipe(req);
Angular httpclient1
2
3
4
5
6
7
8
9
10
11
12
13const formData = new FormData();
formData.append('username', 'QQs');
formData.append('password', btoa('*****'));
const postUrl = 'http://loacalhost:3000/';
const authorizationData = 'Basic ' + btoa('authorizationID:authorizationPassword');
const headers = new HttpHeaders({
'Authorization': authorizationData
});
return this.http.post(postUrl, postData, { headers: headers }).pipe(
map(response => {
})
)
html form1
2
3
4
5<form action="http://authorizationID:authorizationPassword@localhost:3000/" method="post" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="text" name="password" id="password">
<input type="submit" value="Post">
</form>